Using Custom Deleters with std::unique_ptr Members
In object-oriented programming, it is often desirable to utilize member objects managed by unique pointers (std::unique_ptr). However, when dealing with third-party classes that have custom memory management requirements, employing a custom deleter can prove beneficial.
Consider a scenario where you have a class (Foo) with a member managed by a unique pointer (std::unique_ptr
To address this, you can implement a custom deleter within your Foo class, using syntax similar to the following:
class Foo { private: std::unique_ptr<Bar, void(*)(Bar*)> ptr_; // ... public: Foo() : ptr_(create(), destroy) { /* ... */ } // ... };
In this example, create() and destroy() are assumed to be free functions that adhere to the following signatures:
Bar* create(); void destroy(Bar*);
By specifying destroy as the second template argument of the unique pointer, you effectively instruct the pointer to invoke destroy() when the managed object is deleted.
This approach allows you to seamlessly manage the memory of your third-party member object while maintaining the benefits of using unique pointers, such as automatic resource deallocation and ownership semantics.
The above is the detailed content of How Can I Use Custom Deleters with std::unique_ptr Members for Third-Party Classes?. For more information, please follow other related articles on the PHP Chinese website!