Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>No, it's not safe. <code>foo</code> and <code>bar</code> need virtual destructors, otherwise it's undefined what happens when the destructor of <code>shared_ptr</code> deletes the pointer it's holding. Of course, saying that it's not safe isn't the same as saying it should crash.</p> <p>Alternatively, there's some magic[*] built into <code>shared_ptr</code> which means that if you don't cast to <code>foo*</code>, your code becomes safe:</p> <pre><code>fooptr f(fb1); barptr b(fb2); </code></pre> <p>Either with the virtual destructor, or if you take out the casts, when shared_ptr comes to delete the pointer, the compiler will "know" how to adjust the pointer back to its original type, in order to call the correct destructors and free the memory.</p> <p>The magic only works because <code>fb1</code> is type <code>foobar*</code>, though. Without the virtual destructor, the following is still unsafe:</p> <pre><code>foo *fb = new foobar(); fooptr f(fb); </code></pre> <p>If you use <code>shared_ptr</code> like this, then there's no risk of doing that:</p> <pre><code>fooptr f(new foobar()); </code></pre> <p>You can also avoid the problem that in your code, that if the second call to <code>new foobar()</code> throws an exception, the first object is leaked. If you're going to use <code>shared_ptr</code> to manage memory for you, then you need to get the memory under management as quickly as possible:</p> <pre><code>fooptr f(new foobar()); barptr b(new foobar()); </code></pre> <p>Now if the second line throws, <code>f</code> will be properly destructed and will delete the object.</p> <p>[*] "magic" = a constructor template, which stores in the <code>shared_ptr</code> a pointer to a function which will cast the stored pointer back to the correct type, and then delete it.</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