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!

user4581301
  • 33,082
  • 7
  • 33
  • 54
Maestro
  • 2,512
  • 9
  • 24

2 Answers2

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

eerorika
  • 232,697
  • 12
  • 197
  • 326
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
    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 '21 at 23:19