Reputation: 64266
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()))
Upvotes: 3
Views: 10691
Reputation: 19
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 the corresponding templates to fulfill the standard casts defined in c++.
Upvotes: 0
Reputation: 231093
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.
Upvotes: 12