The problem of return reference to local variable [duplicate]
Possible Duplicate:
Returning reference to a local variable
I happened to find this code return 5. It's OK to write it this way or should definitely be avoid?
int& f() {
int i = 5;
return i;
}
int main(){
cout<<f()<<endl;
}
If it works, it works only by accident. This is undefined behavior and should definitely be avoided.
The moment that f returns, there are no longer any guarantees as to what happens to the memory where i
lived and what happens when you try to access it.
The compiler warning is correct — you can't do that. i
is likely to be overwritten at some unexpected time.
Either do
int f() { // don't return reference
int i = 5;
return i;
}
int main(){
cout<<f()<<endl;
}
or
int &f( int &i ) { // accept reference
// actually, in the case of modify-and-return like this,
// you should call by value and return by value without
// using any references. This is for illustration.
i = 5;
return i;
}
int main(){
int i
cout<<f(i)<<endl;
}
When the function 'f()' returns, the stack contents will be popped, and the memory address to the variable 'i' will no longer be valid. This code should not be used.
精彩评论