21. Don't try to return a reference when you must return an object

必须返回对象时,别妄想返回其reference

class Rational
{
public:

	Rational(int numerator = 0, int demoninator = 2);
	friend const Rational operator * (const Rational& lhs, const Rational& rhs);	
	...
private:
	int n, d;
}

因为 operator * 返回的是一个Ration对象,所以必定存在一次对象拷贝构造(如果编译器优化,则可省略)。

可以试着返回引用(指针效果一样),函数内部实现有如下几种:

  1. 使用局部对象
const Rational& operator * (const Rational& lhs, const Rational& rh)
{
	Rational result(lhs.n * rhs.n, lhs.d * rhs.d);
	return result;
}

返回局部对象的引用,同返回局部对象的指针一样,将导致未定义行为。

  1. 使用heap对象
const Rational& operator * (const Rational& lhs, const Rational& rh)
{
	Rational* result = new Rational(lhs.n * rhs.n, lhs.d * rhs.d);
	return *result;
}

咋看之下好像没问题,不过这样的话,堆内存的释放就必须由调用者完成。
不能确定调用者用完一定会释放。或者出现下面的调用,一定出现内存泄漏。

Rational w, x, y ,z;
w = x * y * z;

根据规则,先计算y * z, 结果在 * x, 总会出现一次内存泄露。

  1. 使用局部静态都对象
const Rational& operator * (const Rational& lhs, const Rational& rh)
{
	static Rational result(lhs.n * rhs.n, lhs.d * rhs.d);
	return result;
}

确实没有1中那么严重的问题。但是,如果有以下调用,结果总是为true

Ration a, b, c, d;
if ((a * b) == (c * d))
	...;
else
	...;

一个"必须返回新对象"的函数的正确写法是:就让那个返回返回一个新对象。

inline const Rational operator * (const Rational& lhs, const Rational& rh)
{
	Rational result(lhs.n * rhs.n, lhs.d * rhs.d);
	return result;
}

请记住:

绝不要返回pointer或reference指向一个local stack对象,或返回reference指向一个heap-allocated对象,或返回pointer或reference指向一个local static对象而有可能同时需要多个这样的对象。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值