简体   繁体   中英

Return reference in c++ when use Visual Studio and Codeblocks

I am learning C++. I use both visual studio 2015 and codeblocks IDE to code C++. I tried to write a program that returns a reference variable from a function and I get different results(two results) from 2 IDE( Visual Studio 2015 and codeblocks) although I run the same code. I tried writing the following code:

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

I known that it depends on compiler but I want to know Which is correct in this case? Thank in advance!

First note that what determines program behavior is the compiler rather than the IDE (the program you use to write the code). Other factors are what's currently on disk and what you get as input (eg from the user, the Network), the system clock etc.

Now, as @DeiDei correctly points out, you get different behaviour because your func() function returns a reference to a variable that's local to it, and goes out of scope when its execution concludes. Its memory on the stack (or the register associated with it) may become used by other data - and you get no guarantees on what happens when you access it. This is an example of compilable code which has Undefined Behavior when run.

Finally, most compilers will warn you about this - and I'm sure that's true for both compilers used by your IDEs. So you should:

  1. Turn on compiler warning flags.
  2. Read the warnings and address them.

What you're doing is undefined behaviour as you are returning a reference to something that is destroyed when the function goes out of scope. The fact that is works in VS2015 is just chance.

If you want to return a locally created object then either return it by value, or dynamically allocate it and return it as a pointer using either shared_ptr or unique_ptr .

It really is simple. When the function func reaches its last line, the life time of temp dies. Whenever you try to access that value, a segmentation fault will occur which tells you that you are trying to access an illegal memory location.

I really can't explain the reason of your success in Visual Studio more than luck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM