问题描述
C ++ 11引入了新的值类别,其中之一是xvalue
.
C++11 introduced new value categories, one of them is xvalue
.
Stroustrup对它进行了解释,类似于(im
类别):它是一个值,具有身份,但可以从"移出.
It is explained by Stroustrup as something like (im
category): "it is a value, which has identity, but can be moved from".
另一个来源, cppreference 解释:
Another source, cppreference explains:
xvalue
是glvalue
,所以这对xvalue
也是正确的.
And xvalue
is a glvalue
, so this is statement is true for xvalue
too.
现在,我认为如果xvalue
具有身份,那么我可以检查两个xvalue
是否引用同一对象,因此我使用了xvalue
的地址.事实证明,这是不允许的:
Now, I thought that if an xvalue
has identity, then I can check if two xvalue
s refer to the same object, so I take the address of an xvalue
. As it turned out, it is not allowed:
int main() {
int a;
int *b = &std::move(a); // NOT ALLOWED
}
xvalue
具有身份是什么意思?
What does it mean that xvalue
has identity?
推荐答案
xvalue确实具有标识,但是在语言中有一个单独的规则,即一元&
表达式需要一个lvalue操作数.来自[expr.unary.op]:
The xvalue does have an identity, but there's a separate rule in the language that a unary &
-expression requires an lvalue operand. From [expr.unary.op]:
通过将xvalue绑定到引用,可以在执行rvalue-to-lvalue转换后查看xvalue的身份:
You can look at the identity of an xvalue after performing rvalue-to-lvalue conversion by binding the xvalue to a reference:
int &&r = std::move(a);
int *p = &r; // OK
这篇关于"x值具有身份"是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!