Say we have an utility function:
std::string GetDescription() { return "The description."; }
Is it OK to return the string literal? Is the implicitly created std::string object copied?
I thought about always returning it like this:
std::string GetDescription() { return std::move(std::string("The description.")); }
But it’s of course longer and more verbose. We could also assume that compiler RVO will help us a bit
std::string GetDescription() { return std::string("The description."); }
Yet still, I don’t know what it really has to do, instead of what can it do.
is equivalent to this:
which in turn is equivalent to this:
Means when you return
std::string("XYZ")which is a temporary object, thenstd::moveis unnecessary, because the object will be moved anyway (implicitly).Likewise, when you return
"XYZ", then the explicit constructionstd::string("XYZ")is unnecessary, because the construction will happen anyway (implicitly).So the answer to this question:
is NO. The implicitly created object is after all a temporary object which is moved (implicitly). But then the move can be elided by the compiler!
So the bottomline is this : you can write this code and be happy:
And in some corner-cases,
return tempObjis more efficient (and thus better) thanreturn std::move(tempObj).