Yes, it is possible to implement shared_ptr that way. Boost does and the C++11 standard also requires this behaviour. As an added flexibility shared_ptr manages more than just a reference counter. A so-called deleter is usually put into the same memory block that also contains the reference counters. But the fun part is that the type of this deleter is not part of the shared_ptr type. This is called “type erasure” and is basically the same technique used for implementing the “polymorphic functions” boost::function or std::function for hiding the actual functor’s type. To make your example work, we need a templated constructor:
template<class T>
class shared_ptr
{
public:
...
template<class Y>
explicit shared_ptr(Y* p);
...
};
So, if you use this with your classes Base and Derived …
class Base {};
class Derived : public Base {};
int main() {
shared_ptr<Base> sp (new Derived);
}
… the templated constructor with Y=Derived is used to construct the shared_ptr object. The constructor has thus the chance to create the appropriate deleter object and reference counters and stores a pointer to this control block as a data member. If the reference counter reaches zero, the previously created and Derived-aware deleter will be used to dispose of the object.
The C++11 standard has the following to say about this constructor (20.7.2.2.1):
Requires:
pmust be convertible toT*.Yshall be a complete type. The expressiondelete pshall be well formed, shall have well defined behaviour and shall not throw exceptions.Effects: Constructs a
shared_ptrobject that owns the pointerp.…
And for the destructor (20.7.2.2.2):
Effects: If
*thisis empty or shares ownership with anothershared_ptrinstance (use_count() > 1), there are no side effects.
Otherwise, if*thisowns an objectpand a deleterd,d(p)is called.
Otherwise, if*thisowns a pointerp, anddelete pis called.
(emphasis using bold font is mine).