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();
It is dangerous to have a dangling pointer like that as pointers or references to local variables are not allowed to escape the function where local variables live; hence, the compiler throws an error.
The content of a reference variable can only be assigned to another reference variable. At the same time, data references can only be assigned to data reference variables and.
The local variable may be returned to calling scope (the point in the program where the function was called), or it may be logged and discarded when the function ends.
It is usually not a good programming practice to give different variables the same names. If a global and a local variable with the same name are in scope, which means accessible, at the same time, your code can access only the local variable.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With