Here is one way:
{ std::cout << "unique_ptr<Bar, void(void*)>:\n"; std::unique_ptr<Foo, void(*)(void*)> p( new Bar(), [](void*p) -> void { delete static_cast<Bar*>( p ); } );
The main problem with this approach is that unique_ptr supports conversion to a logical "pointer to the base class", but the standard does not guarantee that conversion to void* will then give the same address. In practice, this is only a problem if the base class is not polymorphic and the derived class is polymorphic by introducing vtable ptr and possibly changing the memory layout a bit. But in this possible, but not entirely probable situation, dropping back into a deleter would lead to an incorrect pointer value and a hit.
Thus, the foregoing is not formally safe with respect to such transformations.
To do roughly the same thing that shared_ptr does ( shared_ptr supports conversion to a logical pointer to the base), you will also need to save the original void* pointer along with the deletion.
In general, when you manage the top-most base class, make its destructor virtual.
It takes care of everything.
source share