C ++ allows you to avoid creating and copying additional objects in cases like yours. This is called optimization of the named value. The fact is that you know for sure that after returning the temp object will disappear anyway, and the semantics of the copy constructor should make an equivalent copy of the original object.
Note that there are actually two optimizations here. Without optimization, the temp object will first be copied to the return value in g , and then the returned value will be copied to h2 in main . Named value optimization returns a copy to the return value. Copying from the return value to h2 is canceled because the return value is a temporary object, and copying can also be canceled here.
Please note that unlike other optimizations, these optimizations are allowed even if they change the observed behavior (as in your test program). This is because otherwise this optimization cannot be performed in many cases where it does not matter (indeed, with the exception of debugging output, it should never matter in a well-written program), because the compiler often cannot prove that elite would not change the observed behavior. On the other hand, there is no way to manually delete copies, so it is important that the compiler can do this automatically.
Ultimately, what happens is that the temp object is created directly in the h2 space, so there is already the correct value at the point of the return h2 operator. In other words, due to optimizations temp and h2 are actually the same object.
celtschk Jan 17 '12 at 6:30 2012-01-17 06:30
source share