author:
- luixiao1223
title: ‘返回对象时,别返回reference’
糟糕代码
const Rational& operator*(const Rational& lhs, //这里返回的是一个引用类型。糟糕的点
const Rational& rhs)
{
Rational result(lhs.n * rhs.n, lhs.d * rhs.d);
return result;
}
更糟糕的代码
const Rational& operator*(const Rational& lhs,
const Rational& rhs)
{
Rational* result = new Rational(lhs.n * rhs.n, lhs.d * rhs.d);
return *result; // 谁来释放它呢?因为是在堆上的。
}
泄露的问题
Rational x,w,y,z;
w = x * y * z; // 这中间的变量会没人去释放。
又一堆烂代码
const Rational& operator*(const Rational& lhs,
const Rational& rhs)
{
static Rational result;
result = ...;
return result
}
- 对线程问题
- 另外的问题
(a*b == c*d) //这个表达式问题
正确的写法
inline const Rational operator*(const Rational& lhs,
const Rational& rhs)
{
return Rational(lhs.n * rhs.n, lhs.d * rhs.d);
}
- 编译器回去优化这样的语句。
- 新的C++标准的右值。