[英]What's the difference between an ordinary rvalue reference and one returned by std::forward?
I can't do this: 我不能这样做:
int &&q = 7;
int &&r = q;
//Error Message:
//cannot convert from 'int' to 'int &&'
//You cannot bind an lvalue to an rvalue reference
If I understand correctly, when initializing an rvalue reference, there's a temporary variable got initialized too. 如果我理解正确,在初始化右值引用时,也会初始化一个临时变量。 So
int &&q = 7;
所以
int &&q = 7;
can be considered as: 可以认为是:
int temp = 7;
int &&q = temp;
And when using a reference on the right side, I am actually using the referee. 当在右侧使用参考时,我实际上是在使用裁判。 So
int &&r = q;
所以
int &&r = q;
can be considered as: 可以认为是:
int &&r = temp; //bind an lvalue to an rvalue reference, cause error, understandable
So above is how I understand the compiler error occurs. 所以上面是我理解编译器错误发生的方式。
Why adding std::forward
can solve that? 为什么添加
std::forward
可以解决这个问题?
int &&q = 7;
int &&r = std::forward<int>(q);
I know the std::forward
always returns an rvalue reference, how is the reference returned by std::forward
different from int&&q
? 我知道
std::forward
总是返回右值的参考,如何参考由归国std::forward
来自不同int&&q
?
how is the reference returned by
std::forward
different fromint&&q
?std::forward
返回的引用与int&&q
不同之处是什么?
Their value categories are different. 他们的价值观类别不同。 And note that types and value categories are different things.
请注意,类型和值类别是不同的东西。
q
is a named variable, it's qualified as lvalue , so it can't be bound to rvalue reference. q
是一个命名变量,它被限定为左值 ,因此它不能绑定到右值引用。
(emphasis mine) (强调我的)
the name of a variable, a function, a template parameter object (since C++20), or a data member, regardless of type, such as
std::cin
orstd::endl
.变量的名称,函数,模板参数对象(自C ++ 20以来)或数据成员,无论类型如何,例如
std::cin
或std::endl
。 Even if the variable's type is rvalue reference, the expression consisting of its name is an lvalue expression;即使变量的类型是右值引用,由其名称组成的表达式也是左值表达式;
While rvalue reference returned from function is qualified as xvalue , which belongs to rvalue . 虽然从函数返回的rvalue引用被限定为xvalue ,它属于rvalue 。
a function call or an overloaded operator expression, whose return type is rvalue reference to object, such as
std::move(x)
;函数调用或重载的运算符表达式,其返回类型是对象的右值引用,例如
std::move(x)
;
The difference between the expressions q
and std::forward<int>(q)
is that the former is an lvalue, while the latter is an rvalue (of fundamental category xvalue). 表达式
q
和std::forward<int>(q)
之间的区别在于前者是左值,而后者是左值(基本类别xvalue)。
I've addressed similar concerns in this answer : the point is that q
as an expression is an lvalue , because it has a name. 我在这个答案中解决了类似的问题:关键是
q
作为一个表达式是一个左值 ,因为它有一个名字。 std::forward<int>(q)
(or the equivalent std::move(q)
) are expressions which don't have names, and since they return (unnamed) rvalue references, they are xvalues, which is a subcategory of rvalue and can thus bind to an rvalue reference. std::forward<int>(q)
(或等价的std::move(q)
)是没有名称的表达式,因为它们返回(未命名的)右值引用,它们是xvalues,它是一个子类别rvalue因此可以绑定到右值引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.