What does it mean “xvalue has identity”?

一笑奈何 提交于 2019-12-05 23:31:44

问题


C++11 introduced new value categories, one of them is xvalue.

It is explained by Stroustrup as something like (im category): "it is a value, which has identity, but can be moved from".

Another source, cppreference explains:

a glvalue is an expression whose evaluation determines the identity of an object, bit-field, or function;

And xvalue is a glvalue, so this is statement is true for xvalue too.

Now, I thought that if an xvalue has identity, then I can check if two xvalues 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
}

What does it mean that xvalue has identity?


回答1:


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]:

The result of the unary & operator is a pointer to its operand. The operand shall be an lvalue [...]

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


来源:https://stackoverflow.com/questions/50783525/what-does-it-mean-xvalue-has-identity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!