How do I use emplace vs push with std::vector?

In C++, the `std::vector` container provides two primary methods for adding elements: `push_back` and `emplace_back`. While both can be used to insert elements into a vector, they behave differently regarding how the elements are constructed and added to the container.

Using push_back

The `push_back` method adds a copy of an object to the end of the vector. If you pass an object to `push_back`, it will create a copy, which can involve overhead.

Using emplace_back

The `emplace_back` method, on the other hand, constructs the object in-place. This means it forwards the arguments directly to the constructor of the object being added, leading to potentially better performance since it avoids the extra copy or move operation.

Example


#include <iostream>
#include <vector>

class MyClass {
public:
    MyClass(int x) : value(x) {
        std::cout << "Constructing MyClass with value: " << value << std::endl;
    }

    int value;
};

int main() {
    std::vector vec;

    vec.push_back(MyClass(10)); // Copy construction
    vec.emplace_back(20);        // In-place construction

    return 0;
}
    

std::vector emplace_back push_back C++ performance vector operations