Custom Deleters with std::unique_ptr Members
In C , the std::unique_ptr class offers a convenient way to manage ownership of pointer-based objects. However, if you're working with third-party objects that require a customized deletion process, you may face challenges when using std::unique_ptr as a member of a class.
Consider the following scenario: you have a class with a std::unique_ptr
To utilize std::unique_ptr with such a scenario in a standalone function, you can use a custom deleter:
void foo() { std::unique_ptr<Bar, void (*)(Bar*)> bar(create(), [](Bar* b) { destroy(b); }); ... }
But how can you achieve this when the std::unique_ptr is a member of a class?
Custom Deleters in Class Members
Assuming that create and destroy are free functions with the following signatures:
Bar* create(); void destroy(Bar*);
You can define your Foo class as follows:
class Foo { std::unique_ptr<Bar, void (*)(Bar*)> ptr_; // ... public: Foo() : ptr_(create(), destroy) { /* ... */ } // ... };
In this implementation, you're directly providing the destroy function as the deleter for the std::unique_ptr. By using a free function as a deleter, you avoid the need for lambdas or custom deleter classes.
The above is the detailed content of How Can I Use Custom Deleters with std::unique_ptr Members in a C Class?. For more information, please follow other related articles on the PHP Chinese website!