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

问题描述












$ 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说明:


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.5the 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:

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

08-23 06:23