返回引用局部变量的问题

时间:2010-03-21 19:04:56

标签: c++

  

可能重复:
  Returning reference to a local variable

我碰巧发现这个代码返回5.可以这样写,或者一定要避免?

   int& f() {

     int i = 5; 
     return i;
}

int main(){

    cout<<f()<<endl;    
}

3 个答案:

答案 0 :(得分:10)

如果有效,它只能偶然起作用。这是未定义的行为,绝对应该避免。

f返回的那一刻,不再保证i生存的内存会发生什么,以及当你尝试访问它时会发生什么。

答案 1 :(得分:4)

编译器警告是正确的 - 您不能这样做。 i可能会在某个意外时间被覆盖。

要么

int f() { // don't return reference

     int i = 5; 
     return i;
}

int main(){

    cout<<f()<<endl;    
}

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;    
}

答案 2 :(得分:2)

当函数'f()'返回时,将弹出堆栈内容,变量'i'的内存地址将不再有效。不应使用此代码。