If we consider the following code with g++ or clang, the destructor of the Guard class is not called when the exception is not catched at least in the main function. I made a thew googling, and did not find any usefull information.
I use guard class at lot to implement RAII. Thus, I found this to be quite disapointing, in particular when dealing with ressources such as semaphore.
I though that C++ requires the destructor to be called when an exception is thrown. Is this behaviour standard or is this du to the libstdc++ implementation ?
Thank you for any help or advice in this matter.
#include<iostream>
#include<memory>
struct Guard
{
Guard()
: v(new int)
{
std::cout << "Guard()" << std::endl;
}
~Guard(){
std::cout << "~Guard()" << std::endl;
delete v;
}
private:
int *v;
};
void test(){
auto g = std::make_shared<Guard>();
throw("youch");
}
void test2(){
test();
}
int main(void){
// try{
test2();
// } catch(...){
// }
return 0;
}
P.S. : I do not wish to add a try/catch block in the main function as I appreciate to be able to trace back an exception to the point where it is emitted in the debugger.