Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 532
Aaron S Avatar asked Feb 24 '10 05:02

Aaron S


People also ask

What causes undefined Behaviour in C?

In C the use of any automatic variable before it has been initialized yields undefined behavior, as does integer division by zero, signed integer overflow, indexing an array outside of its defined bounds (see buffer overflow), or null pointer dereferencing.

What is undefined behavior in programming?

So, in C/C++ programming, undefined behavior means when the program fails to compile, or it may execute incorrectly, either crashes or generates incorrect results, or when it may fortuitously do exactly what the programmer intended.

Is NRVO guaranteed?

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

What is copy elision in Javascript?

Copy elision is an optimization implemented by most compilers to prevent extra (potentially expensive) copies in certain situations. It makes returning by value or pass-by-value feasible in practice (restrictions apply).


1 Answers

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.

like image 129
Jerry Coffin Avatar answered Sep 27 '22 21:09

Jerry Coffin