effective_operator= 为什么要返回引用

以一个具体例子进行说明,在程序中加断点调试和观察:

class complex {
public:
	complex(double r = 0., double i = 0.) :real(r), image(i) { cout << "构造" << endl; }
	complex(complex&c) :real(c.real), image(c.image) { cout << "复构" << endl; }
	~complex() { cout << "析构" << endl; }
	complex& operator=(const complex &c) {
		if (this == &c)
			return *this;
		this->real = c.real;
		this->image = c.image;
		cout << "赋值" << endl;
		return *this;
	}
private:
	double real, image;
};
int main() {
	complex c1(1, 1), c2(2, 2), c3(3, 3);
	c1 = c2 = c3;
	system("pause");
	return 0;
}

1.赋值返回引用
对于c1 = c2 = c3,先执行c2 = c3,返回c2的引用,再执行c1 = c2,相当于c1.operator=(c2.operator=(c3));

2.赋值返回对象,不返回引用
对于c1 = c2 = c3,先执行c2 = c3,即c2.operator=(c3)返回的是c2的copy(临时对象),再执行c1 = (c2的copy),返回的是c1的copy(临时对象),执行完毕后,最后程序会自动调用析构函数把2个临时对象释放掉。
上述虽然也完成了连续赋值,但是开销太大,创建和最后释放c1的copy和c2的copy,相比于返回引用额外多调用了2次复构函数和2次析构函数。

对于(c1 = c2) = c3,最后c1的结果是不会和c3相同的,原因如下:先执行c1 = c2,返回的是c1的copy(临时对象),再执行(c1的copy) = c3,相当于执行(c1的copy).operator=(c3),返回的又是一个新的临时对象(由c1的copy产生的新copy)。所以最终c1的结果是不可能和c3相同的。代码如下:

class complex {
public:
	complex(double r = 0., double i = 0.) :real(r), image(i) { cout << "构造" << endl; }
	complex(complex&c) :real(c.real), image(c.image) { cout << "复构" << endl; }
	~complex() { cout << "析构" << endl; }
	complex operator=(const complex &c) {
		if (this == &c)
			return *this;
		this->real = c.real;
		this->image = c.image;
		cout << "赋值" << endl;
		return *this;
	}
private:
	double real, image;
};
int main() {
	complex c1(1, 1), c2(2, 2), c3(3, 3);
	(c1 = c2) = c3;
	system("pause");
	return 0;
}

综上所述,operator= 要返回引用,可以省去很多不必要的麻烦!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值