In this article we will discuss how to use custom deleter with std::shared_ptr.

When a shared_ptr object goes out of scope, its destructor is called. Inside its destructor it decrements the reference count by 1 and if new value of reference count is 0 then it deletes the associated raw pointer.

To delete the internal raw pointer in destructor, by default shared_ptr calls the delete() function i.e.

But its not always that we want to use delete function in destruction, there can be other requirements too like,

If shared_ptr object points to an array instead of a simple pointer,

In its destructor shared_ptr will try to delete the int array i.e. int [] by calling

function, whereas as correct way is using

Adding custom deleter to shared_ptr<>

In such case we can pass a callback to shared_ptr’s constructor, that will be called from its destructor for deletion i.e.

Custom Deleter as function Pointer

Pass the function pointer in constructor of shared_ptr to provide custom deleter i.e.

Check complete example as follows,

Ouput:

Custom Deleter as Lambda Function or Function Object

We can also attach Function objects and Lambda functions as callback i.e.,

There might be other cases when we don’t need to delete any memory we just need to releasing memory or resources to a pool etc.

Check out an example with dummy implementation of Memory Pool and Custom Deletor.

Output:

 

Click Here to Subscribe for more Articles / Tutorials like this.