Possible Duplicate:
Returning the address of local or temporary variable
Can a local variable’s memory be accessed outside its scope?
Even knowing what happens as a result of the following snips it would be helpful to understand how it is happening. Four questions follow.
Given:
int& foo()
{
int i = 1;
return i;
}
And knowing that in the following a reference to the local named i is de-referenced into a temp that is assigned to intVal and local i disappears at the end of foo()
int intVal = foo();
First question - in the following, the right hand side of the expression is the same as above so is this a case where the compiler sees the left hand side and, based on context, knows not to de-reference the returned reference, and instead to create a new reference is initialized with it?
Second question - and this alone makes the local i stick around while intRef is in scope?
int& intRef = foo();
Third question - bellow intPtr gets address of local i. So, is the compiler using the context of the assignment and deciding to not de-reference to get a value before taking the address of the reference (rather than say taking the address of a temp containing the de-referenced value)?
Fourth question - does local i stick around while intPtr is in scope?
int* intPtr = &foo();