I have got some confused about shared_ptr.
Say, I 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, so it should crash when the program exit? Or it is safe ?
A
shared_ptr<base>can safely take ownership of aderived*, even ifbasedoes not have a virtual destructor.However, this only works if
shared_ptrknows what the most derived type of the object is when it takes ownership of it. If you were to remove the caststhen you’d definitely be okay. With the casts, the
shared_ptrcannot know what the most-derived type of the object is when it takes ownership of it, so the behavior is undefined, just as if you had said:The best thing to do is to follow the rule that “a base class destructor should be either public and virtual, or protected and nonvirtual.”