I make a demo code like below:
#include <iostream>
using namespace std;
class Test {
public:
Test();
~Test();
Test(const Test&);
};
Test::Test(const Test& rhs) {
cout << "do copy constructor function" << endl;
}
Test::Test()
{
cout << "do constructor function" << endl;
}
Test::~Test() {
cout << "do deconstructor function" << endl;
}
Test fun1() {
Test tmp;
return tmp; // NRVO
}
int main() {
Test t1 = fun1();
return 0;
}
I run it under VS2017 release mode, and c++ standard is set to c++17. The result is as expected, copy constructor has not been run.
But when I comment out the self-defined copy constructor and run it again:
#include <iostream>
using namespace std;
class Test {
public:
Test();
~Test();
};
Test::Test()
{
cout << "do constructor function" << endl;
}
Test::~Test() {
cout << "do deconstructor function" << endl;
}
Test fun1() {
Test tmp;
return tmp; // NRVO
}
int main() {
Test t1 = fun1();
return 0;
}
It turns out NRVO is invalid, because constructor runs once while deconstructor runs twice. So why would that be?