Copy constructor in C ++

I have this code

#include <iostream> using namespace std; class Test{ public: int a; Test(int i=0):a(i){} ~Test(){ cout << a << endl; } Test(const Test &){ cout << "copy" << endl; } void operator=(const Test &){ cout << "=" << endl; } Test operator+(Test& p){ Test res(a+pa); return res; } }; int main (int argc, char const *argv[]){ Test t1(10), t2(20); Test t3=t1+t2; return 0; } 

Conclusion:

 30 20 10 

Why is the copy constructor not called here?

+4
source share
3 answers

This is a special case called Return Value Optimization , in which the compiler is allowed to optimize time intervals.

+11
source

I assume you are curious about the line Test t3=t1+t2;

The compiler is allowed to optimize the copy structure. See http://www.gotw.ca/gotw/001.htm .

+4
source

As others have said, simply optimizing the copy constructor call is what happens if you turn off these optimizations.

 barricada ~$ g++ -o test test.cpp -O0 -fno-elide-constructors barricada ~$ ./test copy 30 copy 134515065 -1217015820 20 10 
+4
source

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


All Articles