2

AS I know a Destructor works the reverse order to the Constructor:

  • Constructor initializes member data (in ctor-init list) then executes its body.

  • Destructor executes its body then destroys member data (in Destruction phase).

  • I know that a Destructor shouldn't throw an exception and if it does so then it should itself handle that exception.

** For curiosity sake: If a destructor raises an exception without handling it there then should it Destroy member data or leaves them un-freed? (Because it leaves prematurely and thus the Destruction phases is skipped).

 struct Bar{};

 struct Foo{
     ~Foo()noexcept(false){
         throw 1024;// leaves here prematurely
     }

     Bar b{};
 };

So does Foo's Dtor frees b after throwing without handling the exception?

** I know I shouldn't do that but just to understand more how exceptions handling work. Thank you!

3
  • 1
    Based on my experiments, it will. Consider it stack unwinding, I guess. However, I'm not sure if this is the standard behavior.
    – yeputons
    Feb 25, 2021 at 22:21
  • 2
    good read: stackoverflow.com/questions/130117/… Feb 25, 2021 at 22:21
  • @NathanOliver: Thanks for the good link.
    – Maestro
    Feb 26, 2021 at 23:03

2 Answers 2

2

If a destructor raises an exception without handling it there then should it Destroy member data

Yes.

So does Foo's Dtor frees b after throwing without handling the exception?

b has a trivial type so its "destructor" does nothing. But yes, the member is destroyed. Members aren't "freed".

1

I haven't tried it but according to the C++ Primer, if a real class destructor throws without catching the exception its self then Terminate is called, ending the program.

1
  • 1
    That is not exactly correct. Although since C++11 destructors are implicitly noexcept one can override that, before that one could throw by default. The advice comes from a different situation - during stack unwiding due to a thrown exception the destructors of local variable are obviously still called, if such destructor calls, the program will terminate. There is no other sane thing to do but throwing from destructor on itself is allowed yet strongly discouraged.
    – Quimby
    Feb 25, 2021 at 23:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.