Reputation: 183
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;
}
Upvotes: 3
Views: 303
Reputation: 30489
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.
Upvotes: 4