【发布时间】:2011-07-14 05:59:02
【问题描述】:
可能重复:
Can a local variable's memory be accessed outside its scope?!
这是一个代码:
#include <iostream>
using namespace std;
double &GetSomeData()
{
double h = 46.50;
double &hRef = h;
return hRef;
}
int main()
{
double nonRef = GetSomeData();
double &ref = GetSomeData();
cout << "nonRef: " << nonRef << endl;
cout << "ref: " << ref << endl;
return 0;
}
nonRef 被打印为 46.5 ref 不正确。
第一个输出行为是正确的还是只是运气好?
谢谢
【问题讨论】:
-
这已经被问过(不止一次)。 Accepted answer 收到了 1642 个赞(迄今为止)...
-
Eric Lippert 做了完美的类比。巧合的是,直到刚才我才阅读他的回答的第一条评论:)
标签: c++ compiler-construction pass-by-reference