Search code examples
c++destructordynamic-memory-allocation

Default Destructor V.S. A Simply Defined Destructor


I wrote this to analyse the behavior of the destructor function of a class and its effect on memory deallocation, but the result seems to be a bit surprising to me:

class test {
public:
    test() {}
    ~test() {} //<-----Run the program once with and once without this line.
};

int main()
{
    test x;
    test *a(&x);
    cout << "a before memory allocation: " << a << endl;
    a = new test;
    cout << "a after memory allocation and before delete: " << a << endl;
    delete a;
    cout << "a after delete: " << a << endl;

    return 0;
}

With default destructor the result is: enter image description here But with my own destructor it's: enter image description here Isn't the second result erroneous? Because somewhere I read that:

the deallocation function shall deallocate the storage referenced by the pointer, rendering invalid all pointers referring to any part of the deallocated storage.

Maybe I'm not following it correctly(especially due to the difficult English words used!). Would you please explain to me why is this happening? What's exactly the difference between my simply defined destructor and the C++ default destructor? Thanks for your help in advance.


Solution

  • If a is a (non-null) pointer to an object, then operation delete a triggers the destructor of the object to which a is pointing to (the default destructor or a specific one) and finally frees the memory that had been allocated for this object. The memory to which a has pointed is not a valid object any more, and a must not be dereferenced any more. However, delete a does not set the value of pointer a back to a specific value. Actually I'm surprised that delete a in your case changed the value of a; I cannot reproduce this behaviour.