What is the difference between push_back and emplace_back in C++?
#include <iostream>
#include <string>
#include <vector>
struct Item {
Item(std::string n, int q) : name(std::move(n)), qty(q) { std::cout << "construct " << name << '\n'; }
Item(const Item& o) : name(o.name), qty(o.qty) { std::cout << "copy " << name << '\n'; }
Item(Item&& o) noexcept : name(std::move(o.name)), qty(o.qty) { std::cout << "move " << name << '\n'; }
std::string name;
int qty;
};
int main() {
std::vector<Item> v;
v.reserve(4); // avoid moves caused by growing
v.push_back(Item("pen", 1)); // builds a temporary, then moves it
v.emplace_back("book", 2); // builds directly in the vector
}
Output
construct pen
move pen
construct book
emplace_back avoids one move. For simple types the difference is small, and push_back is fine. See Vectors.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |