0

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.

Thomas
  • 95
  • 7

1 Answers1

0

You are dealing with implementation defined behavior. Per the standard [except.handle]

If no matching handler is found, the function std::terminate() is called; whether or not the stack is unwound before this call to std::terminate() is implementation-defined

So g may or may not be destroyed based on what implementation you are using. You will not be able to rely on this always being handled the same way.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
  • Thank you for this precise answer. I must say that this undefined behaviour is pretty frustrating. Indeed, I was not aware that one have to set an exception handler to be sure that RAII does work in all cases. – Thomas Apr 19 '16 at 18:22