You can see this behavior in compiler versions Visual Studio 2017 15.6, Clang 4, GCC 7, and above. Despite the name of the paper and what you might read on the Internet, the new rules do not guarantee copy elision. Instead, the new value category rules are defined such that no copy exists in the first place.
Guaranteed copy elision redefines a number of C++ concepts, such that certain circumstances where copies/moves could be elided don't actually provoke a copy/move at all. The compiler isn't eliding a copy; the standard says that no such copying could ever happen. Consider this function: T Func() {return T();}
GCC provides the -fno-elide-constructors option to disable copy-elision. This option is useful to observe (or not observe) the effects of return value optimization or other optimizations where copies are elided. It is generally not recommended to disable this important optimization.
A followup to this post. Consider the following:
class C; C foo();
That is a pair of valid declarations. C
doesn't need to be fully defined when merely declaring a function. But if we were to add the following function:
class C; C foo(); inline C bar() { return foo(); }
Then suddenly C
needs to be a fully defined type. But with guaranteed copy elision, none of its members are required. There's no copying or even a move, the value is initialized elsewhere, and destroyed only in the context of the caller (to bar
).
So why? What in the standard prohibits it?
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