jeudi 5 mai 2022

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.

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

Aucun commentaire:

Enregistrer un commentaire