什么是悬空参考?

Jay*_*esh 0 c++ reference undefined-behavior

以下程序给我运行时错误(分段错误(SIGSEGV))。

#include <iostream>
using namespace std;

int& bar()
{
    int n = 10;
    return n;
}

int main() {
    int& i = bar();
    cout<<i<<endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我的老师告诉我,这是一种不确定的行为,因为悬挂参考。是吗 如果是,那么如何避免呢?

Des*_*tor 5

是的,这确实是未定义的行为,因为您将返回对自动变量的引用,该引用将在bar()完成执行时销毁

您可以通过以下方式避免这种情况:

#include <iostream>
using namespace std;

int& bar()
{
    static int n = 10;
    return n;
}

int main() {
    int& i = bar();
    cout<<i<<endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,静态变量n不会在bar()完成执行时被销毁,而在您的程序终止时将被销毁。

  • 请注意,使用静态变量会丧失线程安全性。 (3认同)