By pointing the pointer ( p ) to a dynamically allocated object, delete performs two functions:
- It calls the dynamically allocated object's destructor. Note that when
~MyClass() completes, destructors are called for any member variables of the class. - It frees the memory occupied by the dynamically allocated object.
It does not look for member variables of the object for other pointers; he does not free another memory and does nothing.
If you need to free the memory pointed to by intArray , you need to delete in the MyClass destructor.
However, in almost all C ++ code, you do not need to worry about this. You should use smart pointers such as shared_ptr , unique_ptr , auto_ptr and scoped_ptr to automatically control dynamically allocated objects. Manual resource management is difficult at best and should be avoided when possible.
This is part of a broader idiom related to the area of resource management (SBRM, also called resource initialization, or RAII). This is by far the most important design pattern to understand and use everywhere in your C ++ code.
If in your class you specified this instead:
boost::scoped_ptr<int> intArray;
then when the scoped_ptr<int> object is destroyed, it will free the pointer that it holds. Then you do not need to do any work to manually destroy the object.
In well-written, modern C ++ code, you rarely need to manually use delete . Smart pointers and other SBRM containers should be used to manage any type of resource that needs to be cleared, including dynamically allocated objects.
In your second example, given a linked list that looks like this:
x -> y -> z -> 0
you will have an order of operations that looks like this:
delete x; x.~MyClass(); delete y; y.~MyClass(); delete z; z.~MyClass(); delete 0; [free memory occupied by z] [free memory occupied by y] [free memory occupied by x]
Items in the linked list will be destroyed in reverse order.