Ptr sharing

class Object { };
Class Derived : public Object { };

boost::shared_ptr<Object> mObject(new Derived); // Ok

But how to pass it in boost::shared_ptr<Derived>?

I tried something like: static_cast< boost::shared_ptr<Derived> >(mObject)and it failed.

The only working idea:

boost::shared_ptr<Derived> res(new dynamic_cast<Derived*>(mObject.get()))

+3
source share
2 answers

DO NOT pass the result of the cast to the new shared_ptr constructor. This will cause two shared_ptrs to think that they belong to this object, and both will try to delete it. The result will be a double and likely failure.

shared_ptr has translation functions specifically for this.

+12
source

You can try

class Object { };
Class Derived : public Object { };

boost::shared_ptr<Object> mObject = new Derived; // OK
boost::shared_ptr<Derived> mDerived = 
    boost::static_pointer_cast<Derived, Object>(mObject); // OK

Boost has appropriate templates for performing standard drops defined in C ++.

0
source

Source: https://habr.com/ru/post/1794903/


All Articles