Chapter 11. Avoid Writing Code in Destructors

In the previous chapter, we discussed why you should try to avoid writing copy constructors and assignment operators at all. In this chapter we discuss why you should avoid writing code in the destructor. I am not saying that the destructor method should not exist, just that if you do write one, it’s a good idea to design your class so that the destructor is empty. The following is acceptable:

virtual ~MyClass() {}

We will use the term an empty destructor when talking about a destructor that has no code inside the curly brackets.

There are several reasons why you might need to write a destructor:

  • In a base class, you might want to declare it virtual, so that you can use a pointer to the base class to point to an instance of a derived class.

  • In a derived class, you do not have to declare it virtual, but might like to do so for the sake of readability.

  • You might need to declare that the destructor does not throw any exceptions.

Let’s consider the last reason more closely. It is widely accepted in the C++ literature that throwing exceptions from a destructor is a bad idea. This is because destructors are often called when an exception is already thrown, and throwing a second one during this process would lead to the termination (or crash) of your program, which is probably not your intention. Therefore, in some classes, destructors are declared as follows (this example comes from the file scpp_assert.hpp):

virtual ~ScppAssertFailedException() ...

Get Safe C++ now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.