Following on from a comment I made on this:
passing std::vector to constructor and move semantics
Is the std::move
necessary in the following code, to ensure that the returned value is a xvalue?
std::vector<string> buildVector()
{
std::vector<string> local;
// .... build a vector
return std::move(local);
}
It is my understanding that this is required. I have often seen this used when returning a std::unique_ptr
from a function, however GManNickG made the following comment:
It is my understanding that in a return statement all local variables are automatically xvalues (expiring values) and will be moved, but I'm unsure if that only applies to the returned object itself. So OP should go ahead and put that in there until I'm more confident it shouldn't have to be. :)
Can anyone clarify if the std::move
is necessary?
Is the behaviour compiler dependent?
You're guaranteed that
local
will be returned as an rvalue in this situation. Usually compilers would perform return-value optimization though before this even becomes an issue, and you probably wouldn't see any actual move at all, since thelocal
object would be constructed directly at the call site.A relevant Note in 6.6.3 ["The return statement"] (2):
To clarify, this is to say that the returned object can be move-constructed from the local object (even though in practice RVO will skip this step entirely). The normative part of the standard is 12.8 ["Copying and moving class objects"] (31, 32), on copy elision and rvalues (thanks @Mankarse!).
Here's a silly example:
Contrast this with returning an actual rvalue reference:
I think the answer is no. Though officially only a note, §5/6 summarizes what expressions are/aren't xvalues:
The first bullet point seems to apply here. Since the function in question returns a value rather than an rvalue reference, the result won't be an xvalue.
Altough both,
return std::move(local)
andreturn local
, do work in sense of that they do compile, their behavior is different. And probably only the latter one was intended.If you write a function which returns a
std::vector<string>
, you have to return astd::vector<string>
and exactly it.std::move(local)
has the typestd::vector<string>&&
which is not astd::vector<string>
so it has to be converted to it using the move constructor.The standard says in 6.6.3.2:
That means,
return std::move(local)
is equalvalent towhereas
return local
only isThis spares you one operation.
To give you a short example of what that means:
This will output