3

In the following code:

    class Object
    {
    public:
        int a, b, c;
        Object() 
        {
            cout << "Creating an object.." << endl;
        }
        ~Object()
        {
            cout << "Deleting an object.." << endl;
        }
    };

    int main(int argc, char *[]) 
    {
        Object *obj = &(Object()); // Why is the destructor called here?
        obj->a = 2; // After the destruction, why didn't this cause an access violation?
        cout << obj->a; // Prints 2.
        getchar();
        return 0;
    }

The Output is:

Creating an object..
Deleting an object..
2

In the above code, why is the destructor called in the line Object *obj = &(Object());? It may be because that Object() returns a temporary object. If it is so, why didn't the next line cause an access violation as the value of obj is the address of deleted temporary object?

Alex
  • 245
  • 1
  • 2
  • 6
  • 5
    What happens is called *undefined behaviour*. You are de-referencing a dangling pointer. It can seem to work, but it cannot be said to work. – juanchopanza Aug 30 '14 at 08:55
  • It's not supposed to compile in the first place. – jrok Aug 30 '14 at 08:56
  • Actually, it won't compile with `taking address of temporary [-fpermissive]` warning. – raina77ow Aug 30 '14 at 08:57
  • 1
    The destructor is called because you're creating a temporary object just to get its address: `&(Object())`. Temporary objects get destroyed immediately after the line they appear in. After that, you're fetching a so-called "dangling pointer". This sometimes might work, but sometimes might not. – Luka Aug 30 '14 at 08:58
  • In this example it works (no access violation) since the pointer is to memory on the stack, which will be valid even tough the d'tor was called, and until you go out of the functions scope. – Moshe Magnes Aug 30 '14 at 09:14

0 Answers0