Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

Push_back vs emplace_back

I'm somewhat confused with respect to the contrast between push_back and emplace_back.
void emplace_back(Type&& _Val);
void push_back(const Type& _Val);
void push_back(Type&& _Val);

As there is a push_back over-burden taking a value reference I don't exactly see what the motive behind emplace_back becomes?
by

2 Answers

espadacoder11
emplace_back shouldn't take an argument of type vector::value_type, but instead variadic arguments that are forwarded to the constructor of the appended item.

template <class... Args> void emplace_back(Args&&... args);

It is possible to pass a value_type which will be forwarded to the copy constructor.

Because it forwards the arguments, this means that if you don't have rvalue, this still means that the container will store a "copied" copy, not a moved copy.

std::vector<std::string> vec;
vec.emplace_back(std::string("Hello")); // moves
std::string s;
vec.emplace_back(s); //copies

But the above should be identical to what push_back does. It is probably rather meant for use cases like:

std::vector<std::pair<std::string, std::string> > vec;
vec.emplace_back(std::string("Hello"), std::string("world"));
// should end up invoking this constructor:
//template<class U, class V> pair(U&& x, V&& y);
//without making any copies of the strings
sandhya6gczb
The short answer is that std::vector emplace_back forwards parameters to the constructor and avoids any extra copy or move operation required when using std::vector push_back. push_back may construct a temporary object, which then gets moved into the vector; whereas, emplace_back just forwards the argument(s) and constructs it directly in place with no copies or moves needed.

Login / Signup to Answer the Question.