Quick Q: Which is more efficient, push_back(move(var)) or emplace_back(var)? -- StackOverflow

Quick A: 1. Those cases are not equivalent. 2. Emplace is more for when you don't already have a named object of the correct type...

Recently on SO:

Efficiency of C++11 push_back() with std::move versus emplace_back() for already constructed objects

In C++11 emplace_back() is generally preferred (in terms of efficiency) to push_back() as it allows in-place construction, but is this still the case when using push_back(std::move()) with an already-constructed object?

For instance, is emplace_back() still preferred in cases like the following?

std::string mystring("hello world");
std::vector<std::string> myvector;

myvector.emplace_back(mystring);
myvector.push_back(std::move(mystring));
// (of course assuming we don't care about using the value of mystring after)

Additionally, is there any benefit in the above example to instead doing:

myvector.emplace_back(std::move(mystring));

or is the move here entirely redundant, or has no effect?

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.