All cases are correct. All of them will build a temporary one and apply the copy constructor of the return type. Mandatory, if there is no copy constructor, the code will not be executed.
RVO will occur in all three cases on most compilers. The only difference is the last when the standard does not force it. This is because you have a named variable. But most compilers are smart enough to apply RVO to it ... the later a named variable is declared, and the fewer conversions it applies, the more likely it is to apply RVO to a named variable.
By the way, returning the link is, of course, possible, as you could see in another code. What you should not do is return the link t to the local object.
std::string& get_a_string2() { std::string str("hello"); return str;
Will produce a compile-time error, as you know. However,
std::string& get_a_string2(std::string& str) {
Will work great. In this case, construction or copying is not provided. The function simply returns a reference to its argument.
Alexandre Bell Sep 08 '09 at 14:21 2009-09-08 14:21
source share