Is weak_ptr a base class and shared_ptr a derived class?

I have a structure that manages objects that come from the base class Entity, but does not control their lifetime. I want this structure to be given weak pointers, such as weak_ptr<Entity>so that it can know if the object was destroyed elsewhere.

However, outside the control structure in which the shared pointer lives, I want the shared pointer to be more specific shared_ptr<SpecificEntity>(SpecificEntity uses Entity as a base class).

Is there a way to accomplish this or something like this?

+5
source share
1 answer

. shared_ptr<Derived> shared_ptr<Base> , std::static_pointer_cast std::dynamic_pointer_cast, , – .. , . :

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

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

std::shared_ptr<Base> r = q;

++ 11-:

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

std::shared_ptr<Base> p = p0;

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

All Articles