# More Effective C++ 条款20

class Rational {

public:

Rational(int numerator = 0, int denominator = 1);

...

int numerator() const;

int denominator() const;

};

// 有关为什么返回值是const的解释，参见条款6,

const Rational operator*(const Rational& lhs,

const Rational& rhs);

// 一种不合理的避免返回对象的方法

const Rational * operator*(const Rational& lhs,

const Rational& rhs);

Rational a = 10;

Rational b(1, 2);

Rational c = *(a * b);             //你觉得这样很“正常”么？

//一种危险的(和不正确的)方法，用来避免返回对象

const Rational& operator*(const Rational& lhs,

const Rational& rhs);

Rational a = 10;

Rational b(1, 2);

Rational c = a * b;                          // 看上去很合理

// 另一种危险的方法 (和不正确的)方法，用来

// 避免返回对象

const Rational& operator*(const Rational& lhs,

const Rational& rhs)

{

Rational result(lhs.numerator() * rhs.numerator(),

lhs.denominator() * rhs.denominator());

return result;

}

// 一种高效和正确的方法，用来实现

// 返回对象的函数

const Rational operator*(const Rational& lhs,

const Rational& rhs)

{

return Rational(lhs.numerator() * rhs.numerator(),

lhs.denominator() * rhs.denominator());

}

Rational(lhs.numerator() * rhs.numerator(),

lhs.denominator() * rhs.denominator());

Rational a = 10;

Rational b(1, 2);

Rational c = a * b;                          // 在这里调用operator*

// the most efficient way to write a function returning

// an object

inline const Rational operator*(const Rational& lhs,

const Rational& rhs)

{

return Rational(lhs.numerator() * rhs.numerator(),

lhs.denominator() * rhs.denominator());

}

"Yeah, yeah," you mutter, "optimization, schmoptimization. Who cares what compilers can do? I want to know what they do do. Does any of this nonsense work with real compilers?" It does. This particular optimization — eliminating a local temporary by using a function's return location (and possibly replacing that with an object at the function's call site) — is both well-known and commonly implemented. It even has a name: the return value optimization. In fact, the existence of a name for this optimization may explain why it's so widely available. Programmers looking for a C++ compiler can ask vendors whether the return value optimization is implemented. If one vendor says yes and another says "The what?," the first vendor has a notable competitive advantage. Ah, capitalism. Sometimes you just gotta love it.

• 0
点赞
• 0
收藏
觉得还不错? 一键收藏
• 打赏
• 0
评论
12-04 71
12-03 126
12-05 551
12-07 362
12-08 91
12-04 140
12-04 144
12-08 433
12-04 95
12-03 363
12-04 26
12-08 142

### “相关推荐”对你有帮助么？

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助

zhc

¥1 ¥2 ¥4 ¥6 ¥10 ¥20

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