Fork me on GitHub Fork me on GitHub

EC读书笔记系列之11:条款20、21

条款20 宁以pass-by-reference-to-const替换pass-by-value

记住:

★尽量以pass-by-reference-to-const替换pass-by-value。前者通常高效,并可避免切割问题

★以上规则并不适用于内置类型,以及STL的迭代器函数对象。那些应用pass-by-value

 

条款21 必须返回对象时,别妄想返回其reference

记住:

★绝不要返回pointer或reference指向一个local stack对象(如函数里的局部对象);或返回pointer或reference指向一个heap-allocated对象;或返回pointer或reference指向一个local static对象而有可能同时需要多个这样的对象。(条款4已经为“在单线程环境中合理返回一个reference指向一个local static对象”提供了一份设计实例)

---------------------------------------------------------------------------

绝不要返回pointer或reference指向一个local stack对象这个好理解,在此不举例

 

特地举例说明如下情况的危险性:

返回pointer或reference指向一个local static对象而有可能同时需要多个这样的对象:

const Rational& operator*( const Rational &lhs, const Rational &rhs ) {
    static Rational result;  //local static对象
    result = ...;
    return result; //这里返回的是引用
}
若客户代码如下:
bool operator==( const Rational &lhs, const Rational &rhs );
Rational a,b,c,d;
...
if( ( a*b ) == ( c*d ) ) {  //总是为true!!!!!!!!!!!!
  …
}
else {
  …
}

if语句永远为true,∵两次operator*调用的确各自改变了static Rational对象值,但由于它们返回的都是reference,∴调用端看到的永远是static Rational对象的“现值”(我理解为即最新计算出来的那个值,∴两者一样!!)。

 

posted @ 2015-11-05 09:38  墨城烟雨  阅读(183)  评论(0编辑  收藏  举报