Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()))

like image 774
Max Frai Avatar asked Jul 09 '26 13:07

Max Frai


1 Answers

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.

like image 157
bdonlan Avatar answered Jul 12 '26 02:07

bdonlan