【C++】拷贝构造函数的剖析

1.  首先看下下面一个例子

<span style="font-size:14px;">#include <iostream>
 
using namespace std;
 
class Rational
{
	friend const Rational operator+(const Rational& a, const Rational& b);
	public:
		Rational(int a = 0, int b = 1): m(a), n(b)
		{
			cout << "Rational::Rational(int, int)" << endl;
		}
 
		Rational(const Rational& r): m(r.m), n(r.n)
		{
			cout << "Rational::Rational(const Rational&)" << endl;
		}	
 
		Rational& operator=(const Rational& r)
		{
			if (this == &r)
				return *this;
 
			m = r.m;
			n = r.n;
 
			cout << "Rational::operator=(const Rational&)" << endl;
 
			return *this;
		}	
 
	private:
		int m;
		int n;
};
 
const Rational operator+(const Rational& a, const Rational& b)
{
	cout << "operator+() begin"<< endl;
	Rational temp;
	temp.m = a.m + b.m;
	temp.n = a.n + b.n;
	cout << "operator+() end"<< endl;
	return temp;
}
 
int main(void)
{
	Rational r, a(10, 10), b(5,8);
	r = a + b;
 
	return 0;
}
 
运行结果:
[root@f8s optmize]# g++ temp_object_return_value.cpp -o temp_object_return_value
[root@f8s optmize]# ./temp_object_return_value                                  
Rational::Rational(int, int)
Rational::Rational(int, int)
Rational::Rational(int, int)
operator+() begin
Rational::Rational(int, int)
operator+() end     
Rational::operator=(const Rational&)  // 疑问,这里之前,应该调用拷贝构造函数,但是实际上没有调用
[root@f8s optmize]#</span>

2. 增加编译选项( -fno-elide-constructors),看看结果

<span style="font-size:18px;">[root@f8s optmize]# g++ temp_object_return_value.cpp -o temp_object_return_value -fno-elide-constructors
[root@f8s optmize]# ./temp_object_return_value
Rational::Rational(int, int)
Rational::Rational(int, int)
Rational::Rational(int, int)
operator+() begin
Rational::Rational(int, int)
operator+() end
Rational::Rational(const Rational&)  // 看,这里调用到拷贝构造函数,怎么回事
Rational::operator=(const Rational&)
[root@f8s optmize]#</span>

3. 查看gcc的手册,有这样的解释

-felide-constructors 
这是默认选项。当产生的代码所调用的函数按值返回一个对象时,如果能直接在返回的位置上产生对象,而不是复制构造函数中已构建的对象,这将使代码大大简化。 但如果构造函数具有副作用,这也会引发问题,可以利用 -fno-elide-constructors 关闭这一选项。
到这里,疑惑解决。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值