# 20. 协助完成“返回值优化（RVO）”

[19]最后曾提到了在函数通过传值方式（by value）返回一个对象时，不可避免地要生成一个临时对象，这会严重影响到程序的效率，如下例计算两个分式的乘积：

class CRational{
public:
CRational(int numerator, int denominator)
{
this->numerator = numerator;
this->denominator = denominator;
}
int numer() const        //get numerator
{
return numerator;
}
int denom() const       //get denominator
{
return denominator;
}
private:
int numerator;
int denominator;
};
const CRational operator *(const CRational& lhs, const CRational& rhs)
{
CRational res(lhs.numer() * rhs.numer(), lhs.denom() * rhs.denom());
return res;
}
CRational a(1, 3);
CRational b(2, 3);
CRational c = a * b;     // 调用函数 operator *()

const CRational* operator *(const CRational& lhs, const CRational& rhs)
{
CRational *pres =
new CRational(lhs.numer() * rhs.numer(), lhs.denom() * rhs.denom());
return pres;
}
CRational c = * (a * b);    //调用函数

const CRational& operator *(const CRational& lhs, const CRational& rhs)
{
CRational res(lhs.numer() * rhs.numer(), lhs.denom() * rhs.denom());
return res;
}
CRational c = a * b;           //看起来没啥问题对吧？

const CRational operator *(const CRational& lhs, const CRational& rhs)
{
return res(lhs.numer() * rhs.numer(), lhs.denom() * rhs.denom());
}

CRational c = a * b;

inline const CRational operator *(const CRational& lhs, const CRational& rhs)
{
return res(lhs.numer() * rhs.numer(), lhs.denom() * rhs.denom());
}
CRational c = a * b;
//与下面的语句几乎具有相同的代价
CRational c(a.numer() * b.numer(), a.denom() * b.denom());

参考文献： 《More Effective C++ 35个改善编程与设计的有效方法 中文版》