Smart Pointers: Understanding Custom Deleters and make_ptr Limitation


Smart pointers are one of the most useful features introduced in modern C++. They help manage object lifetimes automatically and reduce common memory-management issues such as memory leaks and dangling pointers.
In my previous article, we discussed unique_ptr, shared_ptr, their memory overhead, and ownership semantics.
But have you ever wondered what happens when the default delete operation is not sufficient to release a resource?
For example:
What if you are managing a file handle that needs fclose()?
What if you are managing a socket that needs to be closed?
What if a resource is allocated by a third-party library and must be released using its own API?
This is where Custom Deleters become useful. In this article, we'll understand how custom deleters work with unique_ptr and shared_ptr, how make_unique() and make_shared() simplify object creation, and what limitations we should be aware of.
1. Understanding make_unique() and make_shared()

Before going into custom deleters, let's quickly revisit how smart pointers are normally created. Consider a simple class:
#include <iostream>
#include <memory>
class MyClass
{
public:
MyClass()
{
std::cout << "Constructor called\n";
}
~MyClass()
{
std::cout << "Destructor called\n";
}
};
int main()
{
auto ptr1 = std::make_unique<MyClass>();
auto ptr2 = std::make_shared<MyClass>();
}Output:
Constructor called
Constructor called
Destructor called
Destructor calledBoth smart pointers automatically destroy their managed objects when their ownership ends.
The difference is in ownership:
unique_ptr provides exclusive ownership.
shared_ptr allows multiple owners to share the same object.
The make_unique() and make_shared() functions simplify object creation and help avoid exposing raw pointers during construction.
2. What is a Custom Deleter?

By default, smart pointers use delete to destroy dynamically allocated objects. However, not every resource is allocated using new, and not every resource should be released using delete.
Let's take the example of a file handle. In C++, we normally open and close files using C library functions:
FILE* file = fopen("data.txt", "r");
// Use file
fclose(file);Here, calling delete on the file handle would be incorrect. We need fclose() to release the resource. Instead of manually remembering to close the file, we can use a smart pointer with a custom deleter.
A custom deleter is simply a callable object that tells the smart pointer how to release its managed resource.
3. Custom Deleter with unique_ptr
Let's implement the file-handling example using unique_ptr.
#include <iostream>
#include <memory>
#include <cstdio>
int main()
{
auto fileDeleter = [](FILE* file)
{
if (file)
{
std::cout << "Closing file\n";
fclose(file);
}
};
std::unique_ptr<FILE, decltype(fileDeleter)> file(
fopen("data.txt", "r"),
fileDeleter
);
if (file)
{
std::cout << "File opened successfully\n";
}
}Output (assuming the file exists):
File opened successfully
Closing fileLet's understand what changed. Normally, we would write:
std::unique_ptr<MyClass> ptr =
std::make_unique<MyClass>();But when using a custom deleter, we need to provide the deleter as the second template parameter.
std::unique_ptr<FILE, decltype(fileDeleter)>In the above example:
FILE is the managed resource type.
decltype(fileDeleter) is the type of our lambda.
fileDeleter is the actual callable object.
When the smart pointer goes out of scope, it invokes the custom deleter instead of using the default delete operation.
std::unique_ptr does not provide a make_unique() overload that accepts a custom deleter. When a custom deleter is required, we construct the unique_ptr directly.
4. Custom Deleter with shared_ptr
Can we use custom deleters with shared_ptr as well? Absolutely! The difference is that the custom deleter is passed as a constructor argument rather than as a template parameter.
#include <iostream>
#include <memory>
#include <cstdio>
int main()
{
auto fileDeleter = [](FILE* file)
{
if (file)
{
std::cout << "Closing file\n";
fclose(file);
}
};
std::shared_ptr<FILE> file(
fopen("data.txt", "r"),
fileDeleter
);
if (file)
{
std::cout << "File opened successfully\n";
}
}Notice the difference:
// unique_ptr
std::unique_ptr<FILE, decltype(fileDeleter)>
// shared_ptr
std::shared_ptr<FILE>Unlike unique_ptr, the deleter type is not part of the shared_ptr template type. Internally, the deleter is stored in the shared pointer's control block.
Conceptually we can visualize this using below diagram:
shared_ptr
+-------------------+
| Object Pointer |
| Control Block Ptr |
+-------------------+
|
v
Control Block
+-------------------+
| Reference Count |
| Weak Count |
| Custom Deleter |
| Allocator Info |
+-------------------+
|
v
FILE HandleWhen the last shared owner releases the resource, the control block invokes the custom deleter.
This makes it possible to share ownership of resources that require special cleanup operations.
5. Why Can't We Pass Custom Deleters to make_unique() and make_shared()?
This is an important limitation to understand. We have already seen that custom deleters can be passed directly to smart pointer constructors. But what about:
auto ptr = std::make_unique<MyClass>();
auto ptr = std::make_shared<MyClass>();Neither make_unique() nor make_shared() provides an argument for specifying a custom deleter.
Why? These functions are designed around their default resource-management mechanisms.
make_unique() creates a unique_ptr using its default deleter (delete).
make_shared() creates a shared_ptr using its default destruction mechanism, normally destroying the object and releasing its allocated storage.
If a custom cleanup operation is required, we need to use the appropriate smart pointer constructor. For example, unique_ptr
auto deleter = [](MyClass* ptr)
{
std::cout << "Custom cleanup\n";
delete ptr;
};
std::unique_ptr<MyClass, decltype(deleter)> ptr(
new MyClass(),
deleter
);Example: shared_ptr
auto deleter = [](MyClass* ptr)
{
std::cout << "Custom cleanup\n";
delete ptr;
};
std::shared_ptr<MyClass> ptr(
new MyClass(),
deleter
);Both examples use custom deleters, but we lose some of the advantages offered by the make_* functions.
6. What Are the Drawbacks of Not Using make_* Functions?
Let's understand why make_unique() and make_shared() are generally recommended.
A. make_unique() vs Direct unique_ptr Construction
Consider following snippet:
auto ptr = std::make_unique<MyClass>();Compared with:
std::unique_ptr<MyClass> ptr(new MyClass());Both manage the object correctly. However, make_unique() is generally preferred because it:
Simplifies object creation.
Avoids exposing a raw pointer.
Provides exception safety in complex expressions.
Uses the default deleter without requiring additional configuration.
When a custom deleter is needed, direct construction is unavoidable with the standard unique_ptr interface.
B. make_shared() vs Direct shared_ptr Construction
Consider below snippet:
auto ptr = std::make_shared<MyClass>();Typically, make_shared() performs a single allocation for both the object and its control block.
make_shared()
+-----------------------+
| Control Block |
|-----------------------|
| Reference Count |
| Weak Count |
| Allocator Information |
|-----------------------|
| MyClass Object |
+-----------------------+
Typically: One allocationNow consider:
std::shared_ptr<MyClass> ptr(
new MyClass(),
customDeleter
);Typically, this involves two separate allocations:
Allocation 1
+-------------------+
| MyClass Object |
+-------------------+
Allocation 2
+-------------------+
| Control Block |
|-------------------|
| Reference Count |
| Weak Count |
| Custom Deleter |
+-------------------+As a result, direct construction can introduce:
An additional heap allocation.
More allocation overhead.
Potentially poorer memory locality.
This is one of the reasons make_shared() is generally recommended when a custom deleter is not required.
Note: The single-allocation behavior is typical of standard library implementations, rather than a mandatory memory-layout guarantee.
7. An Interesting Drawback of make_shared()
There is another interesting detail worth knowing. make_shared() typically allocates the object and control block together.
Now imagine the following situation:
std::weak_ptr<MyClass> weakPtr;
{
auto sharedPtr = std::make_shared<MyClass>();
weakPtr = sharedPtr;
}
// sharedPtr is destroyed hereAt this point, the strong reference count becomes zero, so the MyClass object is destroyed.
However, the control block must remain alive because weakPtr still refers to it.
With the typical combined allocation used by make_shared(), the allocated memory containing the object and control block may not be released until the last weak_ptr is destroyed.
After shared_ptr destruction:
+-----------------------+
| Control Block |
|-----------------------|
| Reference Count = 0 |
| Weak Count > 0 |
|-----------------------|
| Object Storage |
| (Object destroyed) |
+-----------------------+
Memory allocation still existsThis can matter when managing large objects and long-lived weak references.
It is one trade-off to consider when choosing between make_shared() and direct shared_ptr construction.
8. Key Takeaways
Custom deleters allow smart pointers to manage resources that require special cleanup operations.
unique_ptr accepts a custom deleter as its second template parameter.
shared_ptr accepts a custom deleter through its constructor.
The deleter type becomes part of the unique_ptr type, but not the shared_ptr type.
make_unique() and make_shared() do not support passing custom deleters directly.
make_shared() typically performs a single allocation for the object and control block.
Direct shared_ptr construction with a custom deleter typically requires separate object and control-block allocations.
make_shared() can retain its combined allocation while weak references to its control block still exist.
In general, prefer make_unique() and make_shared() for normal object creation.
However, when dealing with files, sockets, operating-system handles, or resources managed by third-party libraries, custom deleters provide a clean way to integrate resource-specific cleanup with modern C++ ownership management.
Remember: A smart pointer manages ownership, but the deleter defines how the resource is actually released.
Useful technical references:




Comments