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.
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.
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);
}
CustomDeleter
is defined to handle the deletion of int
pointers. It prints a message and then deletes the pointer.std::unique_ptr
: The std::unique_ptr
is constructed with the custom deleter and a raw pointer. When the std::unique_ptr
goes out of scope, CustomDeleter
is called to clean up the resource.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.
Answers to questions are automatically generated and may not have been reviewed.
Learn the techniques and pitfalls of manual memory management in C++