绑定类型为T&& [英] binding a lvalue expression of type T&&

查看:196
本文介绍了绑定类型为T&&的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在过去的几天里,我一直试图抓住一个显而易见的左/右值引用背后的原则。让我们定义一个新的右值引用:

  int&& x = 12; 

x 因此是类型的左值表达式 int&&& 。由于 x 是一个左值,它可以绑定到相同类型的左值引用,即 int&& / code>。这样的左值引用将被定义为:

  int&& & ref_x = x; //非工作代码,只是为了解释

当然,显式定义对引用的引用,并且执行绑定的正确方法如下:

  int& ref_x = x; 

C ++ Primer报告了关于使用引用作为初始化器的以下内容:


当我们使用引用作为初始化器时,我们真的使用引用绑定的
对象


另一方面,左值引用必须与左值表达式的类型匹配。我缺少什么?

解决方案

不, x (作为表达式)是 int 类型的表达式。表达式的值的类型从不是引用。事实上, x 也是一个lvalue,因为它是一个命名的东西。



此外,没有对引用的引用,原因同上:引用绑定到值,值永远不是引用。



如果你感到困惑,只要不断告诉自己:表达式的值总是一个对象类型。表达式的值类别是否仅为l或r仅决定该值可绑定到什么样的事物;它对其类型没有影响。


In the last few days I've been trying to grasp an apparently trivial principle behind lvalue/rvalue references. Let us define a new rvalue reference:

int&& x = 12;

x is therefore an lvalue expression of type int&&. Since x is a lvalue, it can be bound to a lvalue reference of the same type, i.e., a lvalue reference of type int&&. Such a lvalue reference would be defined as:

int&& & ref_x = x; // non-working code, just for the sake of explanation

Of course, it is not possible to explicitly define a reference to a reference, and the correct way to perform the binding is as follows:

int& ref_x = x;

C++ Primer reports the following about using references as initializers:

when we use a reference as an initializer, we are really using the object to which the reference is bound

On the other hand, the lvalue reference must match the type of the lvalue expression. What am I missing? Is reference collapsing involved in this case?

Thanks.

解决方案

No, x (as an expression) is an expression of type int. The type of the value of an expression is never a reference. In fact, x is also an lvalue, since it is a named thing.

Also, there are no references to references, for the same reason: References bind to values, and values are never references.

If you're ever confused, just keep telling yourself: The value of an expression is always an object type. Whether the value category of an expression is l or r only determines what sort of things the value can bind to; it has no effect on its type.

这篇关于绑定类型为T&&的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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