As far as I understand the smart pointers, they are there to avoid memory leaks among other things. However there are often objects which also need to be released, but not by
You can construct both shared_ptr
(signature #3 here) and unique_ptr
(signature #2 here) with custom deleters.
using T = ...;
auto deleter = [](T* x) { delete x; };
// different deleter - different unique_ptr type
// deleter is stored inline
auto x = std::unique_ptr(new T(...), deleter);
// same shared_ptr type regardless of the deleter type,
// deleter is stored in the "shared state"
auto y = std::shared_ptr(new T(...), deleter);
Note, make_shared()
cannot be used to construct a shared_ptr
with custom deleter.