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:
In general is there a way to know the lifetime of an rvalue reference?
Clause 12.2, paragraphs 4-5, says that the lifetime is extended in the second example
There are two contexts in which temporaries are destroyed at a different point than the end of the full-expression. ...
The second context is when a reference is bound to a temporary. The temporary to which the reference is bound or the temporary that is the complete object of a subobject to which the reference is bound persists for the lifetime of the reference except:
(none of the exceptions apply here)