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.
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
}
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.
Custom deleters are useful in several scenarios:
new
/delete
for allocation and deallocation, such as file handles or network connections.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.
Answers to questions are automatically generated and may not have been reviewed.
Learn the techniques and pitfalls of manual memory management in C++