Tag Archives: emplace_back

std::vector::emplace_back()

The emplace_back() method is a C++11 addition to vector that makes it more efficient to add an object to the back of a vector.

Consider the following code:

#include <iostream>
#include <vector>
#include <string>

class X
{
public:
    X(std::string s, int i)
        : s_(s), i_(i)
    {
        std::cout << "Constructor called for " << s_ << i_ << "\n";
    }
    X(const X& other)
        : s_(other.s_), i_(other.i_)
    {
        std::cout << "Copy constructor called for " << s_ << i_ << "\n";
    }
private:
    std::string s_;
    int i_;
};

int main()
{
    std::vector<X> v;
    std::cout << "push_back:" << "\n";
    v.push_back(X("A", 1));
}

An object of a class with 2 member variables initialised in the constructor is first constructed, and added to the end of a vector with push_back().

This is a 2-step process:

  1. Construct the object
  2. Copy it into the vector’s storage

The output from the program shows this process:

push_back:
Constructor called for A1
Copy constructor called for A1

Constructing an object, copying it, and then destroying it when it goes out of scope is not very efficient, and it’s this inefficiency that emplace_back is designed to remove.

emplace_back takes a variable list of arguments, which must match those of one of the object’s constructors, and these are forwarded to that constructor so that the object is constructed in-place.

    std::cout << "emplace_back:" << "\n";
    v.emplace_back("A", 1);

This produces the following output:

emplace_back:
Constructor called for A1

So the unnecessary copy has not happened.

Related