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()))
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With