Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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+p.a);
         return res;
      }
};

int main (int argc, char const *argv[]){
   Test t1(10), t2(20);
   Test t3=t1+t2;
   return 0;
}

Output:

30
20
10

Why isn't the copy constructor called here?

like image 279
shreyasva Avatar asked Dec 01 '22 05:12

shreyasva


2 Answers

This is a special case called Return Value Optimization in which the compiler is allowed to optimize away temporaries.

like image 156
wilhelmtell Avatar answered Dec 20 '22 21:12

wilhelmtell


I assume you're wondering about the line Test t3=t1+t2;

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

like image 25
mkj Avatar answered Dec 20 '22 22:12

mkj