push_back vs emplace_back in C++

Guilin Zhu
2 min readOct 9, 2020

Recently I came across a question regarding how/when to use push_back and emplace_back in C++ for vector or other containers. I believe most people are quite familiar with push_back and they use it a lot when pushing some elements to the vector in C++, however emplace_back function always left me a question as to why this even exists, and how we can use it.

Now after some investigation, I could finally figure out the difference between these two functions. push_back function supports both lvalue and rvalue as an argument, the function signature is as follows:

void push_back(const Type& _Val);

void push_back(Type&& _Val);

we can see that push_back is able to support both lvalue and rvalue with const Type& _val`. For example, if a value is pushed into the vector by calling push_back, a new temporary object will be explicitly created with provided argument, and then push_back copies/move this new object into value, and temporary object will be destroyed.

As for emplace_back, no temporary object is created, the provided argument is created instead in the vector, thus no copy or move constructor is involved.

More intuitive difference is shown below in the figure.

// constructs the elements in place.                                                
emplace_back("element");


//It will create new object and then copy(or move) its value of arguments.
push_back(explicitDataType{"element"});

However, it seems like we should always use emplace_back instead of push_back, since emplace_back has performance enhancement, there will be some cases that these optimizations will make code less safe and less clear, unless performance is improved enough to show up in the application.

Reference:

--

--

Guilin Zhu

Computer Vision, AI & Robotics at Georgia Institute of Technology