Smart pointer | destructor on exception | Sololearn: Learn to code for FREE!


Smart pointer | destructor on exception

Hi I have a class which has user defined destructor and constructor. I am creating shared_ptr of this class. In next few lines of code , there is exception which I am creating intentionally by dividing one number with zero...this is just example and my entire code may throw exception at any point of time and fair chances are there that all exception are not handled yet. I observed that even with smart pointer, destructor is not called. How to do this handling ? I am confused that smart pointer also does not guarantee destructor call ?

8/10/2021 3:23:51 PM

Ketan Lalcheta

2 Answers

New Answer


That's because C++ runtime handles uncaught exceptions by calling std::terminate (). During this event, it is dependent on your language implementation whether any stack unwinding is done or not before calling std::terminate (). ( Afaik clang and some older versions of gcc do it but MSVC and current trunk of gcc does not unwind the stack ) Looks like in your case, it didn't unwound the stack and thus local objects ( including the smart pointer ) are not being destroyed. see this for more info 👇


Yes , in my case it is not unwinding stack... I tried to use custom terminate but it is not hitting that function... Rather visual studio breaks where code is trying to devide by zero