Custom Deleters with std::unique_ptr
What role does the custom deleter in std::unique_ptr
play, and when would you need to use it?
std::unique_ptr
can be customized with a deleter to control how the managed resource is freed. This feature is useful for handling non-standard resource management scenarios.
What is a Custom Deleter?
A custom deleter is a function or function object that defines how a resource should be released when the std::unique_ptr
is destroyed. This is particularly useful when dealing with resources that require specific cleanup actions.
Example
Here's how you can use a custom deleter with std::unique_ptr
:
#include <iostream>
#include <memory>
// Custom deleter function
void CustomDeleter(int* p) {
std::cout << "Custom delete called\n";
delete p;
}
void CustomDeleterExample() {
std::unique_ptr<int, decltype(&CustomDeleter)>
p(new int(10), CustomDeleter);
}
Explanation
- Custom Deleter Function:
CustomDeleter
is defined to handle the deletion ofint
pointers. It prints a message and then deletes the pointer. - Usage with
std::unique_ptr
: Thestd::unique_ptr
is constructed with the custom deleter and a raw pointer. When thestd::unique_ptr
goes out of scope,CustomDeleter
is called to clean up the resource.
When to Use Custom Deleters
- Non-Standard Cleanup: When the resource requires special cleanup procedures, such as closing a file handle or releasing a database connection.
- Integration with C Libraries: When working with C libraries that use their own memory management functions.
Summary
Custom deleters in std::unique_ptr
provide flexibility for managing resources that need special handling upon release. By defining a custom deleter, you can ensure that the resource is properly cleaned up according to your specific requirements.
Managing Memory Manually
Learn the techniques and pitfalls of manual memory management in C++