zoukankan      html  css  js  c++  java
  • 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对象的“现值”(我理解为即最新计算出来的那个值,∴两者一样!!)。

  • 相关阅读:
    测试开发系列之Python开发mock接口(三)
    测试开发系列之Python开发mock接口(二)
    测试开发系列之Python开发mock接口(一)
    python单元测试unittest
    Linux–Nginx攻略
    cookies和session
    Selenium-------ActionChainApi接口详解
    Selenium-----wait的三种等待
    Selenium-Switch与SelectApi接口
    app token session rsp
  • 原文地址:https://www.cnblogs.com/hansonwang99/p/4938456.html
Copyright © 2011-2022 走看看