C++ 之 const references

Posted Pat

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.


 

 

以上是关于C++ 之 const references的主要内容,如果未能解决你的问题,请参考以下文章

❥关于C++之const重载与调用

C++之const关键字的基本使用

C++经典面试题之深入解析const修饰指针的作用

个人学习C++过程中对const的总结:初始化系列之用字面值常量与其他类型的值初始化的区别

C++之引用操作

C++面向对象之封装篇(上)