Question: 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!

Answer: 
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 (e.g. 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](http://stackoverflow.com/questions/2397984/ddg#4105123) 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`.