
On Fri, Feb 17, 2012 at 1:11 AM, Roman Perepelitsa < roman.perepelitsa@gmail.com> wrote:
2012/2/17 Jeffrey Lee Hellrung, Jr. <jeffrey.hellrung@gmail.com>
std::string foo() { std::string result; /*...*/ // would like to "return x;", but instead... result.swap(x); return result; /*...*/ // would like to "return y;", but instead... result.swap(y); return result; }
Simplified RVO rules: If all return statements in a function refer to the same local variable OR if a function returns an ravlue in all cases, the copy can (and in practice will) be elided.
// RVO-enabled: always returns the same local variable. string foo() { string res; if (flag) { res = "hello"; return res; } else { res = "bye"; return res; } }
// RVO-enabled: always returns a temporary. string foo() { if (flag) return "hello"; else return "bye"; }
It's a good practice to make all functions you write RVO-enabled.
So all of these functions are functionally equivalent to simply constructing a std::string object in the calling scope?