dimanche 29 mars 2015

When is it a good time to return by rvalue references?

Question


After reading tons of articles about rvalue references, I know that:



std::string&& f_wrong()
{
std::string s("hello");
return std::move(s);
}


is wrong, and:



std::string f_right()
{
std::string s("hello");
return s;
}


is sufficient for the move constructor of std::string (or any move constructible classes) to be invoked. Also, if the return value is to be used to construct an object, named return value optimization applies, the object will be constructed directly at the target address, so the move constructor will not be invoked:



std::string s = f_right();


My question is: when is it a good time to return by rvalue references? As far as I could think of, it seems like returning an rvalue reference doesn't makes sense except for functions like std::move() and std::forward(). Is it true?


Thanks!


References


C++0x: Do people understand rvalue references? | Pizer's Weblog


return by rvalue reference


C++11 rvalues and move semantics confusion (return statement)


Is returning by rvalue reference more efficient?


Aucun commentaire:

Enregistrer un commentaire