c++ - To use shared_ptr, is it safe ? -
i have got confused shared_ptr.
say, have classes:
class foo { int _f; }; typedef std::shared_ptr<foo> fooptr; class bar { int _b; }; typedef std::shared_ptr<bar> barptr; class foobar : public foo, public bar { int _fb; }; int main () { foobar *fb1 = new foobar(); foobar *fb2 = new foobar(); fooptr f((foo *)fb1); barptr b((bar *)fb2); return 0; }
because b.get() != fb2, should crash when program exit? or safe ?
a shared_ptr<base>
can safely take ownership of derived*
, if base
not have virtual destructor.
however, works if shared_ptr
knows derived type of object when takes ownership of it. if remove casts
fooptr f(fb1); fooptr b(fb2);
then you'd okay. casts, shared_ptr
cannot know most-derived type of object when takes ownership of it, behavior undefined, if had said:
foo* f = new foobar(); delete f;
the best thing follow rule "a base class destructor should either public , virtual, or protected , nonvirtual."
Comments
Post a Comment