这个问题在这里已有答案:
在以下代码中,演示了两个函数 . f1()返回函数作用域中初始化局部变量的引用,f2()返回函数作用域中初始化局部变量的值 .
f2()预计会运行良好,因为本地初始化变量 . 值从堆栈传递到main .
f1()不会起作用,因为局部变量的引用在函数范围之外是无用的 . 但是,两个函数的输出似乎都没问题 .
这是测试代码;
#include
using namespace std;
// function declarations
int& f1();
int f2();
int main()
{
cout << "f1: " << f1() << endl; // should not work!
cout << "f2: " << f2() << endl; // should work
return 0;
}
int& f1() // returns reference
{
int i = 10; // local variable
return i; // returns reference
}
int f2() // returns value
{
int i = 5; // local variable
return i; // returns value
}
输出如下;
f1: 10
f2: 5
为什么f1()工作正常,即使f1()返回局部变量的引用?