This is an optimization known as copy elision, sometimes called "(N) RVO" (for "(named) return value optimization") by those who like acronyms.
In certain circumstances, when an object (conceptually) is created in one place, copied or moved to another, and then destroyed, the program is allowed to create it in its last place. This optimization is allowed even if the processed and / or destructor with deviations have side effects, as in your example.
Return a temporary or local variable from one of these situations. Instead of creating a temp in the frame of the function stack and then copying it to the caller, the program can instead create it directly in the callerβs frame.
When you return *this , the copy cannot be deleted, as *this has a lifetime outside the function. From the perspective of the caller there will be two objects, so the program should actually make a copy:
Cents original; Cents copy = original.Add(42); // "copy" and "original" both exist: the object must have been copied.
For complete information on what operations can be eliminated by this optimization, see C ++ 11 Standard, 12.8 / 31.
source share