I am learning memory management in C++ and I don\'t get the why only some of the destructors are called when leaving scope. In the code below, only obj1 destructor is called
obj1
is an object of type cl1
, with automatic storage duration (It is allocated on the stack, and its lifetime is determined by the scope it is in)
obj1
is an object of type cl1*
. That is, it is a pointer. The pointer also has automatic storage duration, but the object it points to does not. It points to a dynamically-allocated object in the free-store.
When you leave the scope, then the objects with automatic storage duration get destroyed. obj1
gets destroyed, calling your destructor. And obj2
also gets destroyed, but obj2
isn't of type cl1
, so it doesn't call cl1
's destructor. It is a pointer, and it does nothing special when it is destroyed.
Pointers don't own the objects they point to, and so they do nothing to ensure the pointed-to object gets destroyed or cleaned up. (If you want an "owning" pointer, that's what smart pointer classes are for)
Consider that you can easily have multiple pointers pointing to the same object.
If a pointer automatically deleted the object it pointed to, then that would lead to errors. An object pointed to by two different pointers would get deleted twice.
You should use delete
for dynamically allocated objects:
delete obj2;
this calls the destructor and frees memory. You'll be much better off using smart pointers for managing such objects - they will call delete
for you even in case of exception being thrown between new
and delete
.