About constructors and assign operators in C ++

I just created a class like this:

class GreatClass { public: GreatClass(){cout<<"Default Constructor Called!\n";} GreatClass(GreatClass &gc){cout<<"Copy Constructor Called!\n";} GreatClass(const GreatClass &gc){cout<<"Copy Constructor (CONST) Called!\n";} ~GreatClass(){cout<<"Destructor Called.\n";} GreatClass& operator=(GreatClass& gc){cout<<"Assign Operator Called!";return gc;} const GreatClass& operator=(const GreatClass& gc){cout<<"Assign Operator (CONST) Called!";return gc;} }; GreatClass f(GreatClass gc) { return gc; } 

and the main () function has two versions:

version # 1:

 int main() { GreatClass g1; GreatClass G = f(g1); } 

version # 2:

 int main() { GreatClass g1; f(g1); } 

All of them generate SAME output:

 Default Constructor Called! Copy Constructor Called! Copy Constructor Called! Destructor Called. Destructor Called. Destructor Called. 

I don't understand why nothing happens when I assign f(g1) G Which constructor or statement is called at this point?

Thanks.

+6
source share
1 answer

In some cases, compiler implementations are allowed to remove / delete code constructor calls; the example you specify is a good example of using such a script. Instead of creating a temporary object and then copying it to the target object, the object is created directly in the target object, and the copy constructor call is deleted.

This optimization is known as Copy elision through Return Value Optimization .

In addition, when using C ++ 11, moving semantics through rvalue links can be used instead of copy semantics. Even with relocation semantics, compilers can still use RVO.

+13
source

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


All Articles