函数返回引用C ++

时间:2015-06-06 11:40:56

标签: c++ reference

为什么此代码正在打印' 0'?不应该打印' 20'作为对局部变量的参考' x'正在退货?

#include<iostream>
using namespace std;

int &fun()
{
    int x = 20;
    return x;
}
int main()
{
    cout << fun();
    return 0;
}

1 个答案:

答案 0 :(得分:1)

该程序具有未定义的beahaviour,因为它返回对本地对象的引用,该对象通常在退出函数后将被销毁。

正确的函数实现可能看起来像例如

int & fun()
{
    static int x = 20;
    return x;
}

int & fun( int &x )
{
    x = 20;
    return x;
}