For the following code :
#include<iostream>
using namespace std;
class Test
{
public:
Test(const Test &t) { cout<<"Copy constructor called"<<endl;}
Test() { cout<<"Constructor called"<<endl;}
};
Test fun()
{
cout << "fun() Called\n";
Test t;
return t;
}
int main()
{
Test t1;
Test t2 = fun();
return 0;
}
I am really confused regarding when the copy constructor is called ? Like if I am running the above program copy constructor is not called. That means if I am messing up with the parameters passed to the copy constructor (eliminating const keyword) it shouldn't show any compiler error. But its showing
"no matching function for call to 'Test::Test(Test)' "
Moreover, the fun() is returning an object of type test , which is created during fun() execution. Why the copy constructor is not called here ?
int main()
{
fun();
return 0;
}
also if I am making following changes to main function why copy constructor is called only once , not twice ?
int main()
{
Test t2 = fun();
Test t3 = t2;
return 0;
}
Best Answer
It is because copy initialization is used here, not copy constructor, due to the NRVO enabled in your compiler. You should specify
flag on gcc
or compile it with
cl /Od program.cpp
on VS (/O1 and /O2 enables NRVO)C++ : Avoiding copy with the “return” statement