nnolte
nnolte

Reputation: 1780

Why is copy elision an exception to the as-if rule?

Why does the standard allow my compiler to apply copy elision even when it involves visible side effects, thus breaks the as-if rule?

It is somehow plausible'ish for me when one has guaranteed copy elision, because the actual functionality for copy/move (which would invoke visible changes in the program behaviour) does not necessarily have to exist, but why/how was this before C++17?

Is it because a compiler can not generally detect side effects (I don't know whether this is possible)?

Upvotes: 1

Views: 209

Answers (2)

Deduplicator
Deduplicator

Reputation: 45654

Proving things is hard, even if they are obviously true (whether they are true or not). Enabling the compiler to prove things in acceptable time is even harder. And then some side-effects might not actually matter, but how would you inform the compiler?

While copy-elision should not violate the as-if-rule (at least if the compiler knew which side-effeects to ignore in its analysis), the programmer has the freedom to write his types so it does anyway.

Finally, failure to prove that applying copy-elision does not violate the as-if-rule in a specific case might be very costly, as creating a copy of an object might be arbitrarily involved, needing time and space.

Thus, copy-elision was made an exception to the as-if-rule, being allowed regardless.

Now regarding guaranteed copy-elision, one has to concede that the rules are not necessarily completely obvious. Thus, it's a good thing that relying on it is only (?) necessary for performance, not correctness, at least where performance-requirements aren't too stringent..

Upvotes: 2

François Andrieux
François Andrieux

Reputation: 29023

The cases that allow for this optimization involve copies of temporaries. Conceptually, these should have no visible effect but the language allows class writers to put whatever they want in a copy constructor.

As such, copy constructors might sometimes actually have visible side effects. Strictly speaking, the as-if rule may not be applicable.

It was deemed that this optimization was useful enough and the harm minimal enough to be worth including in the language. Consider that this optimization predates move semantics where return values would always be copied.

Upvotes: 6

Related Questions