vendredi 27 décembre 2013

C++: How to handle exception in CTOR

Yesterday I was reading that thread on Linkedin, and I realized once again that the exception handling in/or around a constructor(CTOR) is still an obscure topic as only one commenter mentioned the correct try-catch form for CTOR that can handle every exception even those coming from the initialization list.
The main problem when an exception occur during a CTOR is what have we to do for cleaning memory allocated on the heap.
To summarize the easiest way to handle exception, I produced the following example.

The output will be (I added some comments:
  • object_t CTOR ==> object_t allocation in our initializer list put in a smart_ptr (1)
  •  test_t CTOR ==> here we enter in the test_t CTOR Impl
  • object_t CTOR ==> we allocated a new object (2)
  • … here we have thrown the exception
  • object_t DTOR ==> the smart pointer object is on the stack, so the stack unwinding run and the memory allocation (1) is cleaned
  • here we handle our dynamic allocation ==> we are now in the CTOR catch section, as we have correctly ordered our data member we can check `if (ptr != nullptr)` and delete it if needed.
  • object_t DTOR ==> now the memory allocation (2) is released.
  • exception just to test... ==> as we have and should always RETHROW the exception, we catch it!

Conclusion: If we based all our class on that model, there is no reason anymore to fear about memory leaks.

Aucun commentaire :

Enregistrer un commentaire