【发布时间】:2018-05-24 19:15:49
【问题描述】:
我正在学习 C++。我使用 Visual Studio 2015 和 codeblocks IDE 来编写 C++。我试图编写一个从函数返回引用变量的程序,尽管我运行相同的代码,但我从 2 个 IDE(Visual Studio 2015 和代码块)中得到了不同的结果(两个结果)。我尝试编写以下代码:
#include <iostream>
using namespace std;
class Demo
{
public:
int a;
};
//I wrote a function that returns a reference variable
Demo& func()
{
Demo temp;
temp.a = 1;
return temp;
}
int main()
{
Demo& d = func(); //it error if I run this code on Codeblocks and it run
//smoothly if I run it on Visual Studio 2015
cout<<d.a;
return 0;
}
我知道这取决于编译器,但我想知道 在这种情况下哪个是正确的? 提前致谢!
【问题讨论】:
-
您的代码调用了未定义的行为。您不能返回对局部变量的引用 - 这会导致引用悬空。
-
感谢您的评论,我也希望我们更多地了解 VS2015 和 CodeBlocks 中的两个编译器。
-
什么?!我从 VS2015 得到 "warning C4172: 返回本地变量或临时地址的地址:temp"。请在尝试运行代码之前检查online warning documentation。您只需单击错误列表中的数字即可到达!
-
也许我已经关闭了 VS2015 中的所有警告。我将研究更多以再次打开它。谢谢。
标签: c++ visual-studio codeblocks