Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can we take the address of xvalue

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading