C++ 之 const references

本文深入解析了C++中三种引用类型:lvalue引用、const引用和rvalue引用的区别及应用场景。详细介绍了它们如何帮助程序员更好地控制对象的使用方式,并探讨了编译器优化背后的技术细节。

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.


 

 

转载于:https://www.cnblogs.com/Patt/p/5818598.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值