函数返回c++引用

Function returning reference C++

本文关键字:引用 c++ 返回 函数      更新时间:2023-10-16

为什么这段代码打印'0'?它不应该打印'20'作为对局部变量'x'的引用返回吗?

#include<iostream>
using namespace std;
int &fun()
{
    int x = 20;
    return x;
}
int main()
{
    cout << fun();
    return 0;
}

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

正确的函数实现应该是这样的,例如

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

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