Does a destructor that left prematurely after throwing an unhandled exception frees member data?

Viewed 88

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!

2 Answers

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".

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.

Related