C++ Programming - Destructor Invocation

Destructors are invoked implicitly in the following cases:

* For static objects at program termination
* For local objects when the block in which the object is created exits
* For a temporary object when the lifetime of the temporary object ends
* For objects allocated on the free store using new, through the use of delete
* During stack unwinding that results from an exception

A destructor can also be invoked explicitly. For example:

class C
{
public:
~C() {}
};
void destroy(C& c)
{
c.C::~C(); //explicit destructor activation
}

A destructor can also be explicitly invoked from within a member function of its object:

void C::destroy()
{
this->C::~C();
}

In particular, explicit destructor invocation is necessary for objects that were created by the placement new operator.

Labels:


About this entry