Destructors are probably the most important aspect of c++, it manages resources for you and allows you add code to handle any special cleanup such as handle deallocation, disconnections from sockets, DB's etc.. Bjarne Stroustup also states that this is one of the nice things about destructors:
There have also been positive surprises. The most spectacular has been
the pervasive use of destructors in techniques relating to resource
management and error handling (using exceptions). I knew destructors
were a good idea—after all, you have to reverse the effect of a
constructor—but I didn't realize quite how central they would be to
good use of C++.
Original article: http://msdn.microsoft.com/en-us/magazine/cc500572.aspx
It is also essential to the idiom RAII (Resource Acquisition Is Initialisation) and explained by Bjarne in this article:
http://www.artima.com/intv/modern3.html
You can read this C++ faq on destructors which should help you even more.
I think Als code sample is a fine example, you can also look at the code sample in the wikipedia article which is also another example. The fact that the destructor is called when the object goes out of scope or when delete
is called is very useful. Something I use is a timer object class to time how long certain function calls take:
class myTimer
{
mytimer():startTime( TimeNow() )
{}
~myTimer()
{
printf("time taken :%I64d", TimeNow() - startTime);
}
private:
__int64 startTime;
};
so in my code I would do something like this
myClass::myFunction()
{
myTimer timer; // initiliases time to Now.
someOtherFunc();
} // mytimer object is now out of scope and the destructor is called and prints the time it took