Const引用和左值 [英] Const reference and lvalue

查看:133
本文介绍了Const引用和左值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们不能写 int& ref = 40 ,因为我们需要在右侧的 lvalue 。但我们可以写 const int& ref = 40 。为什么会这样? 40是 rvalue 而不是 lvalue




const T&不需要是左值或者甚至类型
T。在这种情况下:



[1]首先,如果必要,应用到T的隐式类型转换。 / p>

[2]然后,将结果值放在
类型T的临时变量中。



[3]最后,这个临时变量用作
初始化程序的值。


const int& ref = 40 ,临时int变量在幕后创建,ref绑定到这个临时变量。


We cannot write int& ref = 40 because we need lvalue on right side. But we can write const int& ref = 40 . Why is this possible? 40 is rvalue instead lvalue

I know that this is an exception but why?

解决方案

As Stroustrup says:

The initializer for a const T& need not be an lvalue 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.

So, when you type const int& ref = 40, the temporary int variable is created behind the scenes, and ref is bound to this temporary variable.

这篇关于Const引用和左值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆