As I know, there have been come concepts since C 11: lvalue, rvalue, prvalue, xvalue etc.
As my understanding, if a function returns a local variable, it should be a rvalue.
std::string func() { return std::string("abc"); }
auto ret = func(); // func returns a rvalue
And for xvalue, std::move(x)
is a kind of xvalue.
I think I'm right.
Today, my colleague told me that we can't get the address of rvalue, so &func()
is illegal, but we can get the address of xvalue. This is a way to distinguish rvalue and xvalue...
Well, I just tried: int a = 1; std::cout << &std::move(a);
. But the compiler said:
error: taking address of xvalue (rvalue reference)
So is my colleague wrong?
UPDATE
In fact, my colleague misunderstood the meaning of "has identity" and the unary &
operator and I'm confused by him...
Here is a very nice question about this issue: What does it mean "xvalue has identity"?
CodePudding user response:
Your colleague is incorrect. C has always required an lvalue for use with the address of operator. This is called out explicitly in [expr.unary.op]/3:
The operand of the unary
&
operator shall be an lvalue of some typeT
. The result is a prvalue.
If the standard had used glvalue
instead of lvalue
then they would have been correct but per [fig:basic.lval] lvalue
and xvalue
are distinct leaves of glvalue
so xvalue
s are not allowed.