Using Custom Deleters with std::unique_ptr Members
In programming, utilizing a custom deleter with a std::unique_ptr member can provide greater control over the destruction of objects. This article aims to address the question of how to incorporate a custom deleter within a class structure.
Consider a scenario where a class, Foo, contains a member of type std::unique_ptr
void foo() { std::unique_ptr<Bar, void(*)(Bar*)> bar(create(), [](Bar* b){ destroy(b); }); }
This approach allows for the specification of a custom deleter using a lambda expression. The question arises: is there a way to replicate this behavior when std::unique_ptr is utilized as a member of a class?
Solution: Custom Deleter for Class Member
Assuming that create and destroy are free functions, the following solution can be implemented:
class Foo { std::unique_ptr<Bar, void(*)(Bar*)> ptr_; // ... public: Foo() : ptr_(create(), destroy) { /* ... */ } // ... };
In this scenario, the custom deleter is provided directly within the class definition. The destroy function is utilized as the deleter, negating the need for a lambda expression. This approach ensures that the Bar object is properly destroyed when the Foo object goes out of scope.
The above is the detailed content of How to Use Custom Deleters with `std::unique_ptr` Class Members?. For more information, please follow other related articles on the PHP Chinese website!