C++ return时不调用拷贝构造函数 返回值优化

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++中临时对象及返回值优化

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值