Note that there are some explanatory texts on larger screens.

plurals
  1. PODynamic memory and constructor exceptions
    text
    copied!<p>Early today I discovered function try-catch blocks (from <a href="https://stackoverflow.com/questions/75538/hidden-features-of-c/152659#152659">here</a> in fact) and then went on a bit of a research spree - apparently they're main use is it catch exceptions throw in by a constructor initialiser list.</p> <p>Anyway, this sent me thinking about failing constructors and I've got to a stage where I just need a little clarification. This is all just me trying to learn more about the language, so I don't have a <em>practical</em> example, but here goes...</p> <hr> <p>Given this example code:</p> <pre><code>class A { private: B b C *c; //classes B, C &amp; D omitted for brevity as not really relevant D d; public A(int x, int y, int z) }; A::A(int x, int y, int z) try : b( x ) , c( new C(y) ) , d( z ) { //omitted } catch(...) { //omitted } </code></pre> <p>What happens in these cases:</p> <ol> <li>The initialisation of <code>b</code> throws an exception.</li> <li>The initialisation of <code>c</code> throws an exception.</li> <li>The initialisation of <code>d</code> throws an exception.</li> </ol> <p>Specifically, I want to know at least:</p> <ul> <li>what will/may cause a memory leak from <code>new C(y)</code>. <em>I'm thinking only 3? (see <a href="https://stackoverflow.com/questions/1674980/who-deletes-the-memory-allocated-during-a-new-operation-which-has-exception-in">here</a>)</em></li> <li>could you just <code>delete b</code> in the catch? <em>Is dangerous in cases 1 and 2?</em></li> </ul> <p>Obviously, I guess the safest thing to do is to make <code>c</code> a smart pointer. But disregarding that option for the moment, what's the best course of action? </p> <p>Is it safe to set <code>c</code> to <code>NULL</code> in the initialiser, and then place the call to <code>new</code> in the constructor body? </p> <p>That would then mean a <code>delete c</code> must be placed in the catch in case something else throws in the constructor body? Are there safety issues doing that (ie, if it's the <code>c = new C(y);</code> itself that throws)?</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