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.
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.
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.
Compilers often perform Named Return Value Optimization (NRVO) in such cases, but it is not guaranteed.
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).
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.
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