# 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.

• 本文已收录于以下专栏：

举报原因： 您举报文章：More Effective C++ 条款20 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)