If I write the following code:
#include <iostream>
using namespace std;
int main()
{
cout << &(int &&)123 << endl;
return 0;
}
Then g++
complains:
foo.cc: In function ‘int main()’:
foo.cc:7:20: error: taking address of xvalue (rvalue reference)
Ok, thanks to What are rvalues, lvalues, xvalues, glvalues, and prvalues? I get that an xvalue means that it's about to "expire", which makes sense. But now if I do this:
#include <iostream>
using namespace std;
int main()
{
const int &x = (int &&)123;
cout << &x << endl;
return 0;
}
This "works" just fine and will print an address. So, I have a few questions:
- If the value is about to expire, why can I make a reference to it? The reference won't keep the original object alive (right?).
- Does such a reference result in undefined behavior? E.g. because we're referencing an object that may have been destroyed?
In general is there a way to know the lifetime of an rvalue reference?
std::move
will not have its lifetime extended, but apparently "std::move obtains an rvalue reference to its argument and converts it to an xvalue. ". Are you asking about all xvalues, or just prvalues directly casted to&&
? – Nonparous&&
should be a no-op, shouldn't it? – Parlormaid