Summary: In this tutorial, we will learn how to create a custom deleted to delete a smart pointer in C++.

Introduction to Custom Deleter in C++

When a smart pointer of any user-defined type is destroyed, the destructor of the class is invoked giving us the ability to explicitly inspect and modify the delete process.

But that is not the case with smart pointers of a primitive type.

Consider the following program as an example:

Output:

Constructor
Destructor

Note the output, the destructor of the Test class pointer object was called when its instance got destroyed.

We can write more code in that destructor to do more extra things than just printing a sentence.

The same is not possible in the case of the primitive smart pointer because it ain’t got any destructor.

Here comes the custom deleter in rescue.

We can write a specific type of custom delete function that will be called automatically when any smart pointer of that particular type is deleted.

We will shortly see an example of the same, but before that let’s see how can we create a custom delete in C++.

How to Create a Custom Deleter in C++?

The general syntax to create a custom deleter is:

Custom delete function accepts a pointer object of the type same type as the smart pointer object.

Note: Defining a custom deleter is not enough, we have to connect it with the smart pointer object.

To associate a custom deleter with a smart pointer, we have to provide the name of the function to the object during its declaration.

Custom Deleters as Lambda Expression

We can also create a custom deleter as an lambda expression in C++.

The general syntax to create a Custom deleter as lambda expression is:

Note: We have used shared_ptr for the demonstration. We can create custom deleters for any type of smart pointers.

C++ Example using Custom Deleters

Here is an C++ example that creates an custom deleter function for int type smart pointer:

Output:

Deleting integer pointer with value: 5
Delete Successful.

Although Custom deleters rarely come in handy, it makes smart pointers more powerful. Comment below if you have any doubt.

Leave a Reply

2 × 3 =