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.)
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 .
Compilers often perform Named Return Value Optimization (NRVO) in such cases, but it is not guaranteed.
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.
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.
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! :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With