3

I am sure , I am missing a simple thing here ,

I am not not able to call copy constructor in the code. What can be the reason ?

Is compiler optimizing my code ?

#include<iostream>
using namespace std;

class Test
{
public:
int x;
Test(){ 
    x=100;
    cout << "Test() Called\n";
    }
Test(const Test &t) {   
    this->x=t.x;
    cout << "Test-Copy() Called\n";
    }

    };

Test fun()
{
    cout << "fun() Called\n";
    Test t;
    return t;
}

int main()
{
   Test t1;
   Test t2 = fun();
   cout<<t2.x<<endl;
   return 0;
}
zk9099
  • 183
  • 10
  • RVO - Return value optimization. The `fun()` returns a temporary - rvalue and hence possibly the compiler is calling the move constructor instead of the copy constructor. – Vishal Mar 16 '16 at 04:51
  • not a move constructor, I have tried move constructor – Gilson PJ Mar 16 '16 at 05:09
  • @Vishal when RVO happens, neither move nor copy constructor is called. Also, there is no implicit move constructor because there is a user-declared copy constructor. – M.M Mar 16 '16 at 05:21
  • It should not happen in debug build. – zdf Mar 16 '16 at 06:01

1 Answers1

4

Compilers may omit the copy- and move-constructors of class objects even if copy/move constructor and the destructor have observable side-effects. This is called copy ellision.

One such condition is:

If a function returns a class type by value, and the return statement's expression is the name of a non-volatile object with automatic storage duration, which isn't the function parameter, or a catch clause parameter, and which has the same type (ignoring top-level cv-qualification) as the return type of the function, then copy/move is omitted. When that local object is constructed, it is constructed directly in the storage where the function's return value would otherwise be moved or copied to. This variant of copy elision is known as NRVO, "named return value optimization".

If you want to force the call of copy constructor, explicitly break one of the conditions defined above.

Mohit Jain
  • 30,259
  • 8
  • 73
  • 100