Home >Backend Development >C++ >How to Use Custom Deleters with `std::unique_ptr` Member Variables? ```
When working with third-party classes that require a specific deletion mechanism, you may encounter scenarios where you need to use a custom deleter with std::unique_ptr member variables. This article provides a solution for achieving this.
Imagine you have a class Foo with a member variable of type std::unique_ptr. In this scenario, the third-party class Bar has a dedicated create() and destroy() function for object creation and destruction.
In a standalone function, you can use a custom deleter with std::unique_ptr as follows:
void foo() { std::unique_ptr<Bar, void(*)(Bar*)> bar(create(), [](Bar* b){ destroy(b); }); ... }
To achieve the same functionality when working with member variables, here's the solution:
class Foo { std::unique_ptr<Bar, void(*)(Bar*)> ptr_; // ... public: Foo() : ptr_(create(), destroy) { /* ... */ } // ... };
In this code:
This approach allows you to utilize custom deleters for std::unique_ptr member variables conveniently, ensuring proper resource management even for third-party classes.
The above is the detailed content of How to Use Custom Deleters with `std::unique_ptr` Member Variables? ```. For more information, please follow other related articles on the PHP Chinese website!