Search code examples
c++return-value-optimization

Does "Return value optimization" cause undefined behavior?


Reading this Wikipedia article pointed by one of the repliers to the following question:

C++ Copy constructor, temporaries and copy semantics

I came across this line

Depending on the compiler, and the compiler's settings, the resulting program may display any of the following outputs:

Doesn't this qualify for undefined behavior? I know the article says Depending on the compiler and settings but I just want to clear this.


Solution

  • No, it's not undefined behavior. Undefined behavior has a specific definition in the standard (mostly: "behavior, such as might arise upon use of an erroneous program construct or erroneous data, for which this International Standard imposes no requirements.") In this case, the behavior is unspecified, but not undefined.

    The difference is that any execution of anything with undefined behavior makes all the behavior of your program undefined (i.e. anything can happen). With this particular unspecified behavior, only one of two things can happen: either the copy constructor executes, or it doesn't.