Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

With guaranteed copy elision, why does the class need to be fully defined?

Tags:

People also ask

Is copy elision guaranteed?

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.

What is a guaranteed copy?

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();}

How do you avoid copy elision?

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?