Question

Let's say I have the function

#include <string>

std::string const foo()
{
    std::string s = "bar";
    return s;
}

int main()
{
    std::string t = foo();
}

Can a compiler perform (named) return-value optimization for t, even though the types of s and t are both different from the return type of foo due to the const-ness difference?

(If the answer is different for C++03 and C++11 then I'm definitely interested in knowing the C++03 answer.)

Was it helpful?

Solution

There is no way for RVO optimization to break the promise of a const, so there's no problem: RVO can be performed.


However, move semantics is affected by the const. It effectively disables move semantics, that is, calls of a T(T&&) constructor or move assignment operator. So in general, don't use const on a return value.

Scott Meyers originally recommended const on return values, for more sane coding.

Then Andrei Alexandrescu, in his Mojo article for DDJ, noted that henceforth, with move semantics, const on return values should better be banned, and Scott's earlier advice ignored.


Now I never bothered to learn the various specialized RVO acronyms, like NRVO and so on. And a main reason is that these changed meaning halfway through, originally having one meaning with some custom functionality in the g++ compiler. The terminology here is just a mess.

So, if my terminology's wrong and I should really have used some other acronym, then please feel free to correct! :-)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top