The problem of returning a link to a local variable

Possible duplicate:
Returning a reference to a local variable

I happened to find this return code 5. OK to write it this way or should it be avoided?

int& f() { int i = 5; return i; } int main(){ cout<<f()<<endl; } 
-one
c ++
source share
3 answers

If it works, it only works by chance. This behavior is undefined and should be avoided.

The moment f returns, there is no longer any guarantee as to what happens to the memory in which i lives, and what happens when you try to access it.

+10
source share

The compiler warning is correct - you cannot do this. i will most likely be overwritten at some time.

Or 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; } 
+4
source share

When the function "f ()" returns, the contents of the stack will be popped out and the memory address of the variable "i" will no longer be valid. This code should not be used.

+2
source share

All Articles