Note that there are some explanatory texts on larger screens.

plurals
  1. POIs it ever not safe to throw an exception in a constructor?
    primarykey
    data
    text
    <p>I know that it's not safe to throw exceptions from destructors, but is it ever unsafe to throw exceptions from constructors? </p> <p>e.g. what happens for objects that are declared globally? A quick test with gcc and I get an abort, is that always guaranteed? What solution would you use to cater for that situation?</p> <p>Are there any situations where constructors can throw exceptions and not leave things how we expect.</p> <p>EDIT: I guess I should add that I'm trying to understand under what circumstances I could get a resource leak. Looks like the sensible thing to do is manually free up resources we've obtained part way through construction before throwing the exception. I've never needed to throw exceptions in constructors before today so trying to understand if there are any pitfalls.</p> <p>i.e. Is this also safe?</p> <pre><code>class P{ public: P() { // do stuff... if (error) throw exception } } dostuff(P *p){ // do something with P } ... try { dostuff(new P()) } catch(exception) { } </code></pre> <p>will the memory allocated to the object P be released?</p> <p>EDIT2: Forgot to mention that in this particular case dostuff is storing the reference to P in an output queue. P is actually a message and dostuff takes the message, routes it to the appropriate output queue and sends it. Essentially, once dostuff has hold of it, it gets released later in the innards of dostuff. I think I want to put an autoptr around P and call release on the autoptr after dostuff to prevent a memory leak, would that be correct?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    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