#include <iostream>
int foo()
{
return 0;
}
int main()
{
const int& a = foo();
std::cout << &a << std::endl;
}
In this code, a binds to a rvalue. Is it legal to take its address? (And by legal I mean: in the code ill-formed? Am I causing an undefined behaviour?)
This is fine. In C++11 you can even do this:
You can kind of think about temporaries like this (conceptually and in general):
Except if
xis the definition of a reference type, the compiler notes that you’re purposefully referring to the temporary value and extends its lifetime by removing the early destruction code, making it a normal variable.