开发者

The problem of return reference to local variable [duplicate]

开发者 https://www.devze.com 2022-12-24 09:44 出处:网络
This question already has answers here: 开发者_Python百科 Closed 10 years ago. Possible Duplicate: Returning reference to a local variable
This question already has answers here: 开发者_Python百科 Closed 10 years ago.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号