1

In the following code, the getObj() function returns a reference to a local object. This is obviously very bad since the object gets destroyed when the function returns (the ctor and dtor outputs emphasize the objects lifetime). As expected, the compiler (gcc44) gives a respective warning.

#include <iostream>

class Blah {

private:
    int a_;

public:
    Blah(int a) : a_(a) { std::cout << "Constructing...\n"; }
    ~Blah() { std::cout << "...Destructing\n"; }
    void print() { std::cout << a_ << "\n"; }
};

Blah& getObj() 
{
    Blah blah(3);
    return blah; // returning reference to local object
}

int main()
{
    Blah& b = getObj();
    b.print(); // why does this still output the correct value???

    return 0;
}

However, calling print() on the apparently destroyed object still prints the correct value of the private variable a_. This is the output:

Constructing...
...Destructing
3

How can this be? I would have expected all of the objects data to be destroyed as well.

symphonic
  • 165
  • 2
  • 8

3 Answers3

6

It is called undefined behaviour. Anything can happen. What you saw happen is just a subset of "anything".

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
0

Why would it destroy the data? Your mental model of what is going on is, I'm afraid, clearly incorrect. When an object is released from the stack, or from the heap, all that happens is that the memory it was stored in is now flagged as being free for use. The data is still there until something happens to overwrite it.

Jack Aidley
  • 19,439
  • 7
  • 43
  • 70
0

Destruction simply means that the memory is given back to it's original owner (the Operating System). It does not get erased or overwritten. Some operating systems allow you to read any memory, so you can read it and if you are lucky, nobody else aquired this piece of memory and your value is still there. Please note that being lucky is not guaranteed in any way, your program might as well crash and burn.

nvoigt
  • 75,013
  • 26
  • 93
  • 142