When working with a std::unique_ptr member in a class, there are instances where a custom deleter may be required. This is particularly relevant when the member object requires specific cleanup or destruction procedures.
Consider a scenario where your class has a member std::unique_ptr
In a standalone function, you could utilize a std::unique_ptr with a custom deleter like so:
void foo() { std::unique_ptr<Bar, void(*)(Bar*)> bar(create(), [](Bar* b) { destroy(b); }); ... }
Now, let's adapt this approach to a situation where std::unique_ptr is used as a member in a class called Foo:
class Foo { private: std::unique_ptr<Bar, void(*)(Bar*)> bar_; ... public: Foo() : bar_(create(), destroy) { /* ... */ } // ... };
Notice that no lambda or custom deleter is necessary in this implementation because destroy itself serves as the deleter. This allows for a clean and concise way to manage the unique ownership of the Bar member while utilizing its custom destruction procedure.
The above is the detailed content of How Can I Use a Custom Deleter with a `std::unique_ptr` Member Variable?. For more information, please follow other related articles on the PHP Chinese website!