Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Try/catch function blocks are frowned upon, in the same way as goto --there might be some corner case where they make sense, but they are better avoided: when an object fails to be constructed, best thing you can do is fail and fail fast.</p> <p>On you specific questions, when an exception is thrown in a constructor, all fully constructed subobjects will be destroyed. That means that in the case of <code>b</code> it will be destroyed, in the case of <code>c</code>, it being a raw pointer, nothing is done. The simplest solution is changing <code>c</code> to be a smart pointer that handles the allocated memory. That way, if <code>d</code> throws, the smart pointer will be destroyed and the object released. This is not related to the try/catch block, but rather to how constructors work.</p> <p>It is also, in general, unsafe to delete the pointer from the catch block, as there is no guarantee of the actual value of the pointer <em>before</em> the initialization is performed. That is, if <code>b</code> or <code>c</code> throw, it might be the case that <code>c</code> is not 0, but is not a valid pointer either, and deleting it would be undefined behavior. As always there are cases, as if you have a guarantee that neither <code>b</code> nor <code>c</code> will throw, and assuming that a <code>bad_alloc</code> is not something you usually recover from, then it might be safe.</p> <p>Note that if you need to keep a pointer with a raw pointer for some specific reason, it is better to initialize it to 0 in the initialization list, and then create the object inside the construction block to avoid this problem. Remember also that holding more than one (raw) resource directly in a class makes it really hard to ensure that no resource is leaked -- if first resource is created and assigned, and the second one fails, the destructor will not be called and the resource will leak. Again, if you can use a smart pointer you will have one less problem to deal with.</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