Multiple Destructors with C++ Concepts

Get an overview of the need for multiple destructors and how they were implemented before C++20.

Destructors can’t be overloaded. After all, they have no return type and they don’t take parameters. They’re also not really const because they destroy the underlying objects.

Yet, techniques did exist to have multiple destructors in a class before C++20. Those techniques are simplified in C++20.

The need for multiple destructors

We may need multiple destructions for optimization, for example.

Imagine that we have a class template. We want to have destruction depending on the traits of the template parameters. Trivially destructible types can work with the compiler-generated destructor. It’s much faster than the user-defined destructors.

While “resource acquisition is initialization” (RAII)Resource Acquisition Is Initialization or RAII, is a C++ programming technique that binds the life cycle of a resource that must be acquired before use (allocated heap memory, a thread of execution, open socket, open file, locked mutex, disk space, database connection—anything that exists in limited supply) to the lifetime of an object. is great and we should write our classes by default with that paradigm, with a good wrapper we can make non-RAII classes clean up after themselves.

Multiple destructors before C++20

Let’s see how to implement multiple destructors without having access to a C++20 compiler.

The std::conditionalelement lets us choose between two implementations at compile-time. If the condition that we pass in as the first parameter evaluates totrue`, then the whole call is replaced with the second parameter. Otherwise, the call is replaced with the third parameter.

Get hands-on with 1400+ tech skills courses.