Destructor server primarily to relinquish resources acquired either within the constructor or during the lifetime. the lifetime of the class object, again such as freeing a mutal exclsion lock or deleting memory allocated through operator new.
destructor is implicitly called when the object is out of scope, such as the local object goes out of scope, or when program exit, the global object destructors are called. or explicitly when you call the delete operator.
given the following code.
void destructor_life_cycle_test()
{
Account local("Anna live Plurablle", 1000);
Account &loc_ref = global;
auto_ptr<Account> pact(new Account("stephen Dedalus"));
{
Account local_too("Stephen Hero");
// the local_too will destroy before exit the current local space.
}
// the auto_ptr will destruct here
}
can you see which destructor is called at different stage?
So, why do we need to call explicitly the destructor, given the following code,
given the following example.
char *arena = new char[sizeof Image];
Image * ptr = new (arena) Image("Quasimodo");
Image *ptr = new (arena) Image("Esmerelda");
//you cannot delete the ptr, because it will reclaim the memory in addition to call the destructor
delete ptr;
// but instead, you should do something like this:
ptr->~Image();
// and when you finish using the arena memory , you can free the location by this
delete arena;
// it will not call the destructor, because arena is of type char *
it is obvious that we might need explictly call the destructor when we are manually managing the memory and allocation, we need to call the destructor to explicitly manage the life cycle of the object ourselves.