From the following code, If RVO has happened, I expect to see the 2 addresses pointing to the same location, however this is not the case (my compiler is MS VC9.0)
RVO generally applies when you return an unnamed temporary, but not if you return a previously created object.
std::string foo() {
return std::string("hello world"); // RVO
}
std::string foo() {
std::string str("hello world");
bar();
return str; // Not RVO
}
std::string foo(std::string str) {
return str; // Not RVO
}
A more general version is NRVO (Named return value optimization), which also works on named variables.
std::string foo() {
std::string str("hello world");
bar();
return str; // NRVO
}
std::string foo(std::string str) {
return str; // Not NRVO, as far as I know. The string is constructed outside the function itself, and that construction may be elided by the compiler for other reasons.
}
std::string foo(std::string str) {
std::string ret;
swap(ret, str);
return ret; // NRVO. We're returning the named variable created in the function
}