Note that there are some explanatory texts on larger screens.

plurals
  1. POshared_ptr magic :)
    text
    copied!<p><a href="https://stackoverflow.com/questions/3899688/default-virtual-dtor/3899726#3899726">Mr. Lidström and I had an argument</a> :)</p> <p>Mr. Lidström's claim is that a construct <code>shared_ptr&lt;Base&gt; p(new Derived);</code> doesn't require Base to have a virtual destructor:</p> <blockquote> <p><strong>Armen Tsirunyan</strong>: "Really? Will the <em>shared_ptr</em> clean up correctly? Could you please in this case demonstrate how that effect could be implemented?"</p> <p><strong>Daniel Lidström</strong>: "The <em>shared_ptr</em> uses its own destructor to delete the Concrete instance. This is known as RAII within the C++ community. My advice is that you learn all you can about RAII. It will make your C++ coding so much easier when you use RAII in all situations."</p> <p><strong>Armen Tsirunyan</strong>: "I know about RAII, and I also know that eventually the <em>shared_ptr</em> destructor may delete the stored px when pn reaches 0. But if px had static type pointer to <code>Base</code> and dynamic type pointer to <code>Derived</code>, then unless <code>Base</code> has a virtual destructor, this will result in undefined behavior. Correct me if I am wrong."</p> <p><strong>Daniel Lidström</strong>: "The <em>shared_ptr</em> knows the static type is Concrete. It knows this since I passed it in its constructor! Seems a bit like magic, but I can assure you it is by design and extremely nice."</p> </blockquote> <p>So, judge us. How is it possible (if it is) to implement <em>shared_ptr</em> without requiring polymorphic classes to have virtual destructor? Thanks in advance</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload