返回对局部变量的引用 [英] return reference to local variable

查看:85
本文介绍了返回对局部变量的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:













$ b b

这里是一个代码:

  #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;
}

非引用打印OK为46.5
引用不正确。



是第一个输出行为正确还是只是幸运?



感谢

$ b



返回对局部变量的引用未定义行为



关于未定义的行为,



C ++标准部分1.3.24说明:


允许未定义的行为范围,完全忽略不可预测的结果,在以翻译或程序执行期间以环境特征的文件化方式(具有或不具有诊断消息的发布)行为,终止翻译或执行(通过发出诊断消息)。



Possible Duplicate:
Can a local variable's memory be accessed outside its scope?!

Here is a code:

    #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;
}

the nonRef is printed OK as 46.5 the ref is not OK.

is the first output behavior is correct or just got lucky?

Thanks

解决方案

Yes you got lucky.

Returning reference to local variable is Undefined Behavior. Undefined Behavior means anything can happen and a behavior cannot be defined.

Regarding Undefined Behavior,

C++ Standard section 1.3.24 states:

Permissible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message).

这篇关于返回对局部变量的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆