Note that there are some explanatory texts on larger screens.

plurals
  1. POTry/catch block for simple memory allocation into public raw pointer when inside constructor?
    primarykey
    data
    text
    <p>I have a case with a raw pointer that I can't change to a smart pointer because it is part of the interface (and I don't want to break any code using it):</p> <pre><code>struct Foo { Foo(); ~Foo(); int * m_pStuff; // public! }; </code></pre> <p>I don't want to do much in my ctor. Just something like:</p> <pre><code>m_pStuff = new int[dynamically_obtained_size_which_is_greater_than_0]; m_pStuff[0] = 0; </code></pre> <p>And then in the destructor delete it.</p> <p>Now, I wonder if it's really worth surrounding it with a try/catch:</p> <pre><code>Foo::Foo() : m_pStuff(0) { try { m_pStuff = new int[dynamically_obtained_size_which_is_greater_than_0]; m_pStuff[0] = 0; } catch(...) { delete m_pStuff; throw; } } </code></pre> <p>Points I can see against:</p> <ul> <li>More complex code</li> <li>Not really expecting any exception to happen there (unless it run out of space when allocating)</li> <li>Not really expecting the code to change</li> </ul> <p>Points I can see for:</p> <ul> <li>Indicates to potential future coders that they should be careful with anything throwing exceptions and put it in the try block that is already in place</li> <li>If any exception does happen, memory release is taken care of</li> </ul> <p><strong>I am quite undecided: should I surround this with a try/catch or not?</strong> Why? I would like to get your opinions on that.</p> <p>Also, <strong>do you see any possibility of exception other then resulting from out of memory when allocating? And in that case the already allocated memory would be automatically reclaimed, right?</strong></p> <p>Thanks!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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