【发布时间】:2019-07-02 10:18:33
【问题描述】:
#include <iostream>
using namespace std;
int f()
{
int x=1;
return x;
}
int main()
{
const int& s = f();
cout << s << endl;
}
#include <iostream>
using namespace std;
int x=1;
int &f()
{
return x;
}
int main()
{
const int& s = f();
cout << s << endl;
}
这两个程序都是正确的。但是当我使用
int &f()
{
int x=1;
return x;
}
而不是
int f()
{
int x=1;
return x;
}
我收到一个错误:
main.cpp:在函数'int& f()'中:
main.cpp:6:13: 警告:对局部变量“x”的引用返回 [-Wreturn-local-addr]
int x=1;
^
bash:第 7 行:14826 分段错误(核心转储)./a.out
怎么了?
【问题讨论】:
-
f() 函数中的 x 是函数的局部变量,并且在函数返回时被“销毁”(分配在调用堆栈上)。因此,如果您尝试返回对该已破坏变量的引用,则会导致错误。
-
您可能想get a couple of good books 了解变量的生命周期。
标签: c++