Custom Deleters in Smart Pointers
Can you provide an example of using a custom deleter with a std::unique_ptr
and explain its use?
A custom deleter is a powerful feature of std::unique_ptr
that allows you to define a specific way to release a resource. This is particularly useful for resources that require custom cleanup.
Example of Custom Deleter
Let's create an example where we manage a resource that requires a custom cleanup process:
#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)>
ptr(new int(42), CustomDeleter);
std::cout << *ptr; // Output: 42
}
Explanation
Custom Deleter Function: CustomDeleter
is a function that prints a message and then deletes the pointer. It takes a raw pointer as an argument.
void CustomDeleter(int* p) {
std::cout << "Custom delete called\n";
delete p;
}
Using with std::unique_ptr
: The std::unique_ptr
is constructed with the raw pointer and the custom deleter. When the unique_ptr
goes out of scope, it calls CustomDeleter
to release the resource.
std::unique_ptr<int, decltype(&CustomDeleter)>
ptr(new int(42), CustomDeleter);
Output: When the unique_ptr
is destroyed, it outputs "Custom delete called" before deallocating the memory.
When to Use Custom Deleters
Custom deleters are useful in several scenarios:
- Non-Standard Resource Management: When dealing with resources that do not use
new
/delete
for allocation and deallocation, such as file handles or network connections. - Integration with Legacy Code: When interfacing with C libraries that require specific cleanup functions.
- Additional Logging: For debugging purposes, custom deleters can provide additional information when resources are released.
Conclusion
Custom deleters in std::unique_ptr
offer flexibility in managing resources by allowing you to define specific cleanup actions. This can be particularly valuable for non-standard resources or when integrating with existing codebases.
Managing Memory Manually
Learn the techniques and pitfalls of manual memory management in C++