int&& getInt()
{
return 4;
}
int& getLvalueInt()
{
int r = 5;
return r;
}
int main()
{
auto&& ex = getInt();
++ex;
auto& exx = getLvalueInt();
++exx;
}
In this code, getInt() returns 4 into ex and ++ex increases ex to 5 as expected. However when getLvalueInt() is called, ex is overwritten with trash. Why?
Naturally it's impossible to return a dangling reference if no reference type is returned.
The trick with returning reference types is to ensure that the referent is still within its lifetime when the function ends. Returning a reference to a local variable just always returns a dangling reference because the local variable is destroyed at the end of the function. There is no way to extend the referent's life from the call-site.