+ 2

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 ?

10th Aug 2021, 3:23 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
2 Respostas
+ 5
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 👇 https://en.cppreference.com/w/cpp/error/terminate
10th Aug 2021, 4:09 PM
Arsenic
Arsenic - avatar
0
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
10th Aug 2021, 6:31 PM
Ketan Lalcheta
Ketan Lalcheta - avatar