zoukankan      html  css  js  c++  java
  • C++ 之 const references

    extraction from The C++ Programming Language 4th. ed., Section 7.7 References, Bjarne Stroustrup

    To reflect the lvalue/rvalue and const/non-const distinctions, there are three kinds of references:

    • lvalue references: to refer to objects whose value we want to change
    • const references: to refer to objects whose value we do not want to change (e.g., a constant)
    • rvalue references: to refer to objects whose value we do not need to preserve after we have used it (e.g., a temporary)

    Collectively, they are called referencs. The first two are both called lvalue references.

     The obvious implementation of a reference is as a (constant) pointer that is dereferenced each time it is used. It doesn't do much harm to think about references that way, as long as one remembers that a reference isn't an object that can be manipulated the way a pointer is.

     In some cases, the compiler can optimize away a reference so that there is no object representing that reference at run time.

     Intialization of a reference is trivial when the initializer is an lvalue (an object whose address you can take). The initializer for a "plain" T& must be an lvaue of type T.

     The intializer for a const T& need not be an lvaue or even of type T. In such cases:

    1. First, implicit type conversion to T is applied if necessary.
    2. Then, the resulting value is placed in a temporary variable of type T.
    3. Finally, this temporary variable is used as the value of the initializer.

    Consider:

      double &dr=1;      //error: lvalue needed

      const double& cdr{1};  //OK

    The iterpretation of this last initialization might be:

      double temp = double{1};

      cosnt double &cdr {temp};

    A temporary created to hold a reference initializer persists until the end of its reference's scope.

    References to variables and references to constants are distinguished because introducing a temporary for a variable would have been highly error-prone; an assignment to the variable would become an assignment to the -- soon-to-disappear -- temporary. No such problem exists for references to constants, and references to constants are often important as function arguments.


     

  • 相关阅读:
    BZOJ 3150 [Ctsc2013]猴子 ——期望DP 高斯消元
    BZOJ 4569 [Scoi2016]萌萌哒 ——ST表 并查集
    BZOJ 4590 [Shoi2015]自动刷题机 ——二分答案
    BZOJ 3462 DZY Loves Math II ——动态规划 组合数
    BZOJ 4827 [Shoi2017]分手是祝愿 ——期望DP
    BZOJ 4827 [Hnoi2017]礼物 ——FFT
    BZOJ 4826 [Hnoi2017]影魔 ——扫描线 单调栈
    ZOJ 3874 Permutation Graph ——分治 NTT
    UVA 12633 Super Rooks on Chessboard ——FFT
    HDU 2065 "红色病毒"问题 ——快速幂 生成函数
  • 原文地址:https://www.cnblogs.com/Patt/p/5818598.html
Copyright © 2011-2022 走看看