Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Yes, it can leak.</p> <p>If <code>new std::shared_ptr</code> throws, there is nothing to clean up the memory allocated by <code>new int</code>.</p> <p>In general, automatic <code>delete</code> invocations are made only when a constructor throws after a corresponding <code>new</code>.</p> <p>To elaborate, you can rewrite the code as follows:</p> <pre><code>// if 'new' throws, we just get a bad_alloc, nothing leaked int *iptr = new int; // if 'new' throws, nothing will clean up iptr // // if, for whatever reason, ctor of std::shared_ptr&lt;int&gt; throws, // its memory gets reclaimed by an implicit delete, but iptr's target // is still lost. auto *ptrptr = new std::shared_ptr&lt;int&gt;(iptr); // EDIT: If the constructor of shared_ptr fails, it will delete // the memory it is given, though this still doesn't eliminate the // leak that can occur if the above `new` fails. </code></pre> <p>EDIT:</p> <p>The example above, and this explanation, were really meant to indicate that there isn't anything special about <code>std::shared_ptr</code> as compared to any other smart pointer implementation, or some type that accepts a pointer as a constructor argument for that matter.</p> <p>In the latter case, it really depends on what the type's constructor does with its argument. In the case of <code>std::shared_ptr</code>, it most likely will not throw an exception unless it fails to allocate a control block (if that is, in fact, how it is implemented).</p> <p>If the constructor of <code>std::shared_ptr</code> does fail, at least with the implementation I am using (VS2012), it actually <em>does</em> delete the memory it is given.</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