What is the reason the C++ standard allows(requires) compilers to optimize away calls to copy constructor(in certain cases), even though it might contain observable side effects?
If I'm not mistaken, the "as if" rule already allows compilers to optimize unnecessary code away, as long as the resulting program emulates the observable behavior of the abstract machine defined in the standard.
What were the motives behind making an exception rule? Doesn't it create inconsistencies in the language? Is it convenient(or necessary)?
The vast majority of the time, the copy generated by the return would be a needless cost. The rest of the time, it is expected that the copy constructor's side effects would be undone by the destruction of the copy. Things like
std::shared_ptrdo work on copy that can be observed externally, but undoes it on destruction. It is extremely rare for an object's copy construction to have a side effect that would be missed by a copy elision. It's worth it to avoid the performance hit to inconvenience the rare case. It basically is never problematic.