Why does the Copy constructor invoke only when * this returns?

Class Cents(){ int m_val; public: Cents(int x=0){ cout<<"Constructor";} Cents(const Cents& src){ cout<<"Copy constructor"} Cents Add(int val){m_val=val; return *this} // --->(1) } 

Suppose I have a Cents object obj and I call obj.Add()

Now the output will be

Constructor
Copy constructor

So, my guess was here, returning *this to (1), we copy the value of the *this object to the new temporary Cents object. This is why the copy constructor is called.

Now, if I replace the string (1) with

 Cents Add(int val){ Cents temp;return temp;} // --->(2) 

the only way out is

Constructor

Why is the copy constructor not called? Is my assumption about line (1) wrong?

+4
source share
2 answers

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.

+11
source

This is because most compilers perform Optimization of the return value (aka RVO) to save when copying.

+3
source

Source: https://habr.com/ru/post/1497228/


All Articles