Question

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.

Was it helpful?

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.

OTHER TIPS

No. The behaviour is defined to be one of the outputs on the list. Undefined behaviour includes demons flying out of your nose.

See: Nasal Demons

undefined behavior is quite different from implementation defined behavior, which is what's involved here.

Depends what you mean by undefined. I believe what others have said here - by the definition the standards document use. But I also know that when someone says "either this or that, I'm not telling you which" I think of it as undefined behaviour.

It's not a big deal, though, as it should never cause an error. When you define certain methods, you are expected to define them following particular conventions - it's a kind of implicit contract between you, the compiler and the people who will use and maintain your code.

In this case, whether you get a copy-construct etc or the optimised behaviour, the effect is expected to be the same - the caller receives the wanted value. If your copy constructor is printing "Hello World!" or has other inappropriate side-effects, it isn't implementing the expected behaviour for a constructor, so the fault is yours for breaking the contract.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top