2

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"?

Yves
  • 11,597
  • 17
  • 83
  • 180
  • My own take: theoretically, C++ _could_ have been designed to allow `&` on xvalues. Indeed, we can write `T* get_addr(T&& y) { return &y; }` and then use `get_addr(std::move(x))` so defining `&std::move(x)` in that way looks feasible. However, is it a good idea to take the address of an _expiring_ object? Writing `T* p = get_addr(std::move(x));` creates a dangling pointer (pointless). To avoid that, we could extend the lifetime of the xvalue by binding it to a reference, but at that point we have an lvalue to use `&` on. It looks like allowing `&xvalue()` would only be harmful in most cases. – chi May 05 '22 at 15:13

1 Answers1

3

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 type T. 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 xvalues are not allowed.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
  • Yes you are right. In fact my colleague just misunderstood the meaning of "has identity"... Here is a nice question about it: https://stackoverflow.com/questions/50783525/what-does-it-mean-xvalue-has-identity – Yves May 05 '22 at 13:15