C++函数在return一个局部对象的时候,会调用复制构造构造,生成一个临时对象。
例如
MyClass Fun()
{
MyClass tmp
return tmp;
}
函数Fun在return tmp理应会调用MyClass的拷贝构造函数。
但是如下代码用g++编译后运行,并没有调用到复制构造函数。
#include <iostream>
using namespace std;
class MyClass
{
public:
MyClass(){};
MyClass(int a){member = new int(a);};
~MyClass(){cout<<"~~"<<endl;};
MyClass(const MyClass& Clas_);
MyClass& operator=(const MyClass &Clas_);
public:
void set(int c){member = new int(c);};
void showmember() const {cout<<"member addr: "<<this->member<<endl;
cout<<"member value: "<<*(this->member)<<endl;}
private:
int *member;
};
MyClass::MyClass(const MyClass& Clas_)
{
this->member = Clas_.member;
std::cout<<"My compy Contructor"<<endl;
}
MyClass& MyClass::operator=(const MyClass &Clas_)
{
cout<<"operate ="<<endl;
this->member = Clas_.member;
return *this;
}
MyClass fun(MyClass p_)//参数值传递,调用拷贝构造函数
{
MyClass t;//构造函数
t = p_;//重载复制运算符
cout<<"now return "<<endl;
return t;//拷贝构造函数-fno-elide-constructors 需要关闭g++的返回值优化,否则不调用
}
int main()
{
MyClass A;//构造hanshu
MyClass B = fun(A);//拷贝构造函数
return 0;
}
原因是g++进行了返回值优化,省略了两次复制构造函数的调用。g++编译时加参数 -fno-elide-constructors 会关闭返回值优化,就能看到拷贝构造函数的调用
关于返回值优化参数,man g++中如下叙述
-fno-elide-constructors The C++ standard allows an implementation to omit creating a temporary that is only used to initialize another object of the same type. Specifying this option disables that optimization, and forces G++ to call the copy constructor in all cases.
关于临时变量和返回值优化,参见博文 C++中临时对象及返回值优化