【发布时间】:2016-01-19 00:39:18
【问题描述】:
在下面的代码中,演示了两个函数。 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() 返回局部变量的引用?
【问题讨论】:
-
因为你会唤起未定义的行为,而这样做是极限。
-
因为你太幸运了...
-
你预计会发生什么?
-
未定义行为的一种可能性是它有时似乎工作正常。
-
这比 'i++ + ++i' 有更多的重复 :(
标签: c++ reference local-variables return-by-reference return-by-value