C++ emplace_back
Date: 2023-01-24Last modified: 2023-02-28

Table of contents
You should use push_back when:
- You already have a copy of the element that you want to insert into the
- The object you want to insert is cheap to copy.
- The object has a non-explicit copy constructor
You should use emplace_back when:
- You have the arguments to construct the object, but not the object
- The object is expensive to copy.
- The object has a non-explicit constructor that takes the same arguments
In general, use emplace back when building an element in place. When we need to build an object straight inside the container, we should use emplace back() since it will directly generate an object within the container, eliminating the need for a move/copy ().
struct Test {
int a, b;
Test(int x, int y) : a(x), b(y) {}
};
std::vector<Test> v1;
std::vector<Test> v2;
auto start = std::chrono::high_resolution_clock::now();
for (int i = 0; i < 1000000; ++i) {
v1.push_back(Test(i, i));
}
auto end = std::chrono::high_resolution_clock::now();
std::cout << "push_back took "
<< std::chrono::duration_cast<std::chrono::microseconds>(end -
start)
.count()
<< " microseconds\n";
start = std::chrono::high_resolution_clock::now();
for (int i = 0; i < 1000000; ++i) {
v2.emplace_back(i, i);
}
end = std::chrono::high_resolution_clock::now();
std::cout << "emplace_back took "
<< std::chrono::duration_cast<std::chrono::microseconds>(end -
start)
.count()
<< " microseconds\n";
return 0;
Possible output
push_back took 67699 microseconds
emplace_back took 30729 microseconds
References
- [Modern C++ Series — vector push_back or