Is there any advantage of using std::vector::emplace_back
and std::move
together? or it is just redundant since std::vector::emplace_back
will do an inplace-construction?
Cases for clarification:
std::vector<std::string> bar;
First:
bar.emplace_back(std::move(std::string("some_string")));
Second:
std::string str("some_string");
bar.emplace_back(std::move(str));
Third:
bar.emplace_back(std::move("some_string"));
emplace_back
calls to somehthing likeif
args
are basic - non - rvalue-referencedstd::string
, the expression will compile tomeaning the copy constructor will take place. but, if you use
std::move
onstr
, the code will compile toso move semantics takes place. this is a huge performance gain.
do note, that
str
is lvalue, it has a name, so in order to create r-value-reference from it, you must usestd::move
.in the example
the code will compile to
so no temporaries.
the third example is nonsense. you cannot move literals.
In the second version, there is an advantage. Calling
emplace_back
will call the move constructor ofstd::string
whenstd::move
is used, which could save on a copy (so long as that string isn't stored in a SSO buffer). Note that this is essentially the same aspush_back
in this case.std::move
in the first version is unnecessary, as the string is already a prvalue.std::move
in the third version is irrelevant, as a string literal cannot be moved from.The simplest and most efficient method is this:
That requires no unnecessary
std::string
constructions as the literal is perfect-forwarded to the constructor.There is a point of doing so in the second case. Consider this code:
If you change the comment to the line above, you can see that you will end up with two copies of "some_string" (one in
bar
and one instr
). So it does change something.Otherwise, the first one is moving a temporary, and the third is moving a constant string literal. It does nothing.
The whole idea of
emplace_back
is to get rid of copying and moving operations. You just need to pass input parameters ofstd::string
intoemplace_back
. Astd::string
object will be constructed insideemplace_back
method.If you already have a string, it makes sense to use
std::move
. Astd::string
object will be constructed insideemplace_back
by moving data fromstr
.