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 |
|---|
| C++ Templates and Generic Programming |
| C++ STL Containers: map, set, unordered_map, queue and stack |
| C++ Algorithms and Iterators |
| Exercises & Assignments |
|---|
| Write a generic maximum template |
| Count the frequency of words with a map |
| Remove duplicates from a vector and keep the order |