问题
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();
回答1:
Nope, none of those will extend the lifetime of the local variable. Nothing in C++ will have that effect. Local objects in C++ live until the end of the scope in which they are declared, end of story.
The only rule which, at first glance, seems to follow different rules is this:
int foo() {
return 42;
}
int main() {
const int& i = foo();
// here, `i` is a reference to the temporary that was returned from `foo`, and whose lifetime has been extended
}
That is, a const reference can extend the lifetime of a temporary being assigned to it.
But that requires the function to return a value, not a reference, and the callee to bind the return value to a const reference, neither of which are done in your code.
回答2:
In no case (not intVal, not intRef, and not intPtr) does i necessarily stick around after foo returns.
The value on the stack which was previously occupied by i may or may not be changed at any time, after foo returns.
For example (on some CPUs and O/Ses), it is likely to be changed by any subsequent call to a subroutine, and may be changed if a hardware interrupt occurs.
来源:https://stackoverflow.com/questions/13980362/returning-references-to-local-variable