c++ - Is a virtual destructor needed for your Interface, if you always store it in a shared_ptr? -



c++ - Is a virtual destructor needed for your Interface, if you always store it in a shared_ptr? -

since boost::/std::shared_ptr have advantage of type-erasing deleter, can nice things like

#include <memory> typedef std::shared_ptr<void> gc_ptr; int main(){ gc_ptr p1 = new int(42); gc_ptr p2 = new float(3.14159); gc_ptr p3 = new char('o'); }

and correctly delete pointer right deleter beingness saved.

if ensure every implementation of interface gets created shared_ptr<interface> (or make_shared<interface>), need virtual destructor? declare virtual anyways, want know, since shared_ptr delete type initialized (unless custom deleter given).

i still follow mutual rule classes meant derived:

provide either public virtual destructor or protected non-virtual destructor

the reason cannot command of uses, , simple rule means compiler flag if seek delete through wrong level in hierarchy. consider shared_ptr not guarantee phone call appropriate destructor, phone call destructor of static type used argument:

base* foo(); shared_ptr<base> p( foo() );

if base has public non-virtual destructor , foo returns type derives base, shared_ptr fail phone call right destructor. if destructor of base virtual, fine, if protected, compiler tell there error there.

c++ boost c++11 shared-ptr virtual-destructor

Comments

Popular posts from this blog

iphone - Dismissing a UIAlertView -

intellij idea - Update external libraries with intelij and java -

javascript - send data from a new window to previous window in php -