Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/138.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 返回对局部变量的引用_C++_Compiler Construction_Pass By Reference - Fatal编程技术网

C++ 返回对局部变量的引用

C++ 返回对局部变量的引用,c++,compiler-construction,pass-by-reference,C++,Compiler Construction,Pass By Reference,可能重复: 下面是一个代码: #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

可能重复:

下面是一个代码:

    #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;
}
#包括
使用名称空间std;
double&GetSomeData()
{
双h=46.50;
double&hRef=h;
返回hRef;
}
int main()
{
double nonRef=GetSomeData();
double&ref=GetSomeData();
是的,你很幸运

返回对局部变量的引用是未定义的行为。 未定义的行为意味着任何事情都可能发生,并且行为无法定义

关于未定义的行为

C++标准第1.3.24节规定:

允许的未定义行为范围从完全忽略情况和不可预测的结果,到在翻译或程序执行过程中以环境特有的记录方式(有或没有发出诊断消息)行为,再到终止翻译或执行(发出诊断信息)


通常使用*来声明指针变量,还可以在单词后面取消指针到原始变量的引用。&从变量返回地址

我还没有测试过这个,但是下面的工作是否更好

#include <iostream>
using namespace std;

double* GetSomeData()
{
  double h = 46.50;
  return &h;
}

int main()
{
  double nonRef = GetSomeData();
  double* ref = GetSomeData();
  cout << "nonRef: " << nonRef << endl;
  cout << "ref: " << *ref << endl;
  return 0;
}
#包括
使用名称空间std;
double*GetSomeData()
{
双h=46.50;
返回&h;
}
int main()
{
double nonRef=GetSomeData();
double*ref=GetSomeData();

cout如果您只是测试这两条线之间的差异:

double nonRef = GetSomeData();
double &ref = GetSomeData();
试着上课

class test
{
public:
    int x;
    int& getx()
    {
        return x;
    }
};

//Some code
test c;
int nonRef = c.getx();
int &ref = c.getx();

ref = 8;
nonref = c.getx();

在此之后,c.getx()返回8。

您没有抓住要点。在这种情况下,是否使用引用或指针无关紧要。将地址返回到局部变量是未定义的行为。未定义的行为意味着可能发生任何事情,并且无法定义某个行为。这一问题以前已被询问过(不止一次)。已收到1642次投票(到目前为止)…埃里克·利珀特(Eric Lippert)做了完美的类比。巧合的是,我直到刚才才读到关于他的答案的第一条评论:)