在下面的代碼中,演示了兩個函數。 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