Note that there are some explanatory texts on larger screens.

plurals
  1. POGood style for handling constructor failure of critical object
    primarykey
    data
    text
    <p>I'm trying to decide between two ways of instantiating an object &amp; handling any constructor exceptions for an object that is critical to my program, i.e. if construction fails the program can't continue.</p> <p>I have a class SimpleMIDIOut that wraps basic Win32 MIDI functions. It will open a MIDI device in the constructor and close it in the destructor. It will throw an exception inherited from std::exception in the constructor if the MIDI device cannot be opened.</p> <p>Which of the following ways of catching constructor exceptions for this object would be more in line with C++ best practices</p> <p>Method 1 - Stack allocated object, only in scope inside try block</p> <pre><code>#include &lt;iostream&gt; #include "simplemidiout.h" int main() { try { SimpleMIDIOut myOut; //constructor will throw if MIDI device cannot be opened myOut.PlayNote(60,100); //..... //myOut goes out of scope outside this block //so basically the whole program has to be inside //this block. //On the plus side, it's on the stack so //destructor that handles object cleanup //is called automatically, more inline with RAII idiom? } catch(const std::exception&amp; e) { std::cout &lt;&lt; e.what() &lt;&lt; std::endl; std::cin.ignore(); return 1; } std::cin.ignore(); return 0; } </code></pre> <p>Method 2 - Pointer to object, heap allocated, nicer structured code?</p> <pre><code>#include &lt;iostream&gt; #include "simplemidiout.h" int main() { SimpleMIDIOut *myOut; try { myOut = new SimpleMIDIOut(); } catch(const std::exception&amp; e) { std::cout &lt;&lt; e.what() &lt;&lt; std::endl; delete myOut; return 1; } myOut-&gt;PlayNote(60,100); std::cin.ignore(); delete myOut; return 0; } </code></pre> <p>I like the look of the code in Method 2 better, don't have to jam my whole program into a try block, but Method 1 creates the object on the stack so C++ manages the object's life time, which is more in tune with RAII philosophy isn't it?</p> <p>I'm still a novice at this so any feedback on the above is much appreciated. If there's an even better way to check for/handle constructor failure in a siatuation like this please let me know.</p>
    singulars
    1. This table or related slice is empty.
    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