When we get to the end of our use of a class instance, we need to clean up after ourselves.  This is where destructors come into play.  They are similar to constructors in a mirror fashion.  While a constructor creates an instance, a destructor removes an instance.

Destructors And Resource Release

Many languages have a default destructor, much as they have a default constructor.  These methods likely free up some pointers behind the scenes.  However, we also have resources and properties or even notifications that may be needed as part of this process.  That leads us to a process that effectively undoes the creation and initialization steps.  We first release resources (reverse the initialization).  Then we remove the instance from memory (reverse the constructor).

The Important Properties

The challenge with a destructor and cleanup is that many languages do most of this work for us.  The tasks of memory initialization and pointer creation are done under the covers.  Therefore, we can leave the default destructor as is and let the system manage those things.  However, we do often have non-simple attributes like child instances and resources to release like file handles.  These complex attributes and initialization steps are critical to review and address in our destructors.

Keep It Simple

With all of the above in mind, we also need to consider what happens when a destructor fails.  Therefore, it is helpful to have a close or cleanup method that we can call separate from the destructor.  It may seem like splitting hairs, but there is value in handling releasing resources separate from destroying an instance.  This impact comes from destructors often being called more often than we think.  A fat destructor can dramatically slow performance, just as we see in fat constructors.

This multiple-step approach to cleaning up makes it easier to handle each step at a time.  Thus, potential exceptions are addressed individually rather than treating them in a bunch.  That smaller scope will help you avoid headaches and synchronization of getting the system cleaned up.

Rob Broadhead

Rob is a founder of, and frequent contributor to, Develpreneur. This includes the Building Better Developers podcast. He is also a lifetime learner as a developer, designer, and manager of software solutions. Rob is the founder of RB Consulting and has managed to author a book about his family experiences and a few about becoming a better developer. In his free time, he stays busy raising five children (although they have grown into adults). When he has a chance to breathe, he is on the ice playing hockey to relax or working on his ballroom dance skills.

Leave a Reply