Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a C++ compiler perform RVO for a const return value?

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.)

like image 623
user541686 Avatar asked Jan 20 '13 22:01

user541686


People also ask

Can a function return const?

When the function is executed, it returns the copy of the constant object. Therefore, in cases where we need to alter the object's value later, we should avoid using const .

Is return value optimization guaranteed?

Compilers often perform Named Return Value Optimization (NRVO) in such cases, but it is not guaranteed.

Can you move a const variable C++?

Move constructors will only bind to non-const rvalues.Const variables can not be moved from, since move constructors take a non-const (rvalue) reference.

How does return value optimization work?

In the context of the C++ programming language, return value optimization (RVO) is a compiler optimization that involves eliminating the temporary object created to hold a function's return value. RVO is allowed to change the observable behaviour of the resulting program by the C++ standard.


1 Answers

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! :-)

like image 124
Cheers and hth. - Alf Avatar answered Sep 20 '22 16:09

Cheers and hth. - Alf