在下面的代码中,演示了两个函数。 f1()返回函数作用域中初始化局部变量的引用,f2()返回函数作用域中初始化局部变量的值。返回本地变量的参考
由于本地初始化变量,f2()预计可以正常工作。值从堆栈传递到主。
由于本地变量的引用在函数作用域外无用,所以f1()不会工作。但是,两种功能的输出似乎都可以。
这里是测试代码;
#include <iostream>
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()返回局部变量的引用?
因为你唤起了未定义的行为,这样做的天空是极限。 – 101010
因为你一直非常幸运...... – Chiel
你预计会发生什么? – emlai