必须返回对象时,别妄想返回其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对象,所以必定存在一次对象拷贝构造(如果编译器优化,则可省略)。
可以试着返回引用(指针效果一样),函数内部实现有如下几种:
- 使用局部对象
const Rational& operator * (const Rational& lhs, const Rational& rh)
{
Rational result(lhs.n * rhs.n, lhs.d * rhs.d);
return result;
}
返回局部对象的引用,同返回局部对象的指针一样,将导致未定义行为。
- 使用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, 总会出现一次内存泄露。
- 使用局部静态都对象
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对象而有可能同时需要多个这样的对象。