Sometimes when we destroy smart pointer, we need more than just to destroy an object in the heap.

The class in C++ has destructors, hence we can use it to delete class pointers explicitly. But the same cannot be done in case of structures, especially in C because C Structures do not have destructors.

Similarly, the same case may arise in C++ (not often) and in the case, C++ smart pointers provide custom deleters for specialized deletion of smart pointer objects.

Custom Deleters using Function

In this case, we write deleter function which will be called automatically when smart pointer will be deleted.

Syntax for Custom Deleter – Function

Note: It is important to provide deleter function at the declaration of smart pointer.

Custom Deleters using Lambda

Lamda is an anonymous function, that has no name and can be defined inline where you expect it to use it.

Syntax for Custom Deleter – Lambda

Note: Same syntax is also valid for unique_ptr.

C++ Example using Custom Deleters

Output

Custom Deleter

Though Custom deleters rarely come handy, it makes smart pointers more powerful. If you have any doubts then comment below.

Leave a Reply

Close Menu