#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:
int&& a = foo();
a = 123;
You can kind of think about temporaries like this (conceptually and in general):
x = func(); // translated as:
auto __temporary = func();
x = __temporary;
__destruct_value_now_and_not_later(__temporary);
Except if x
is 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.
Yes. Until the variable a
goes out of scope, the temporary it captures is valid. Herb Sutter can explain it better.