weak_ptr of a base class, while the shared_ptr is of a derived class?

c++, c++11, inheritance, shared-ptr, templates

Solution

That's very possible. You can always convert a `shared_ptr<Derived>` to a `shared_ptr<Base>` implicitly, and for the other direction you have `std::static_pointer_cast` and `std::dynamic_pointer_cast`, which do what you'd expect – i.e. you end up with a new pointer of different type that shares ownership with the original pointer. Example:

std::shared_ptr<Base> p(new Derived);

std::shared_ptr<Derived> q = std::static_pointer_cast<Derived>(p);

std::shared_ptr<Base> r = q;

Or, more C++11-style:

auto p0 = std::make_shared<Derived>();

std::shared_ptr<Base> p = p0;

auto q = std::static_pointer_cast<Derived>(p);

Problem

I have a structure that manages objects that derive from a base class `Entity`, but does not control their lifetimes. I want this structure to be given weak pointers like `weak_ptr<Entity>` so that it can know if the object has been destroyed elsewhere. However, outside of the managing structure where the shared pointer lives, I want the shared pointer to be the more specific `shared_ptr<SpecificEntity>` (SpecificEntity uses Entity as a base class). Is there a way to accomplish this, or something like it?

Original source