Search code examples
c++boostcastingshared-ptr

shared ptr casting


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

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

But how to cast it to boost::shared_ptr<Derived> ?

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

The only working idea is:

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


Solution

  • DO NOT pass the result of the cast to a new shared_ptr constructor. This will result in two shared_ptrs thinking they own the object, and both will try to delete it. The result will be a double-free, and a likely crash.

    shared_ptr has cast functions specifically for this.