Why destructor is not called on exception?

I expected A::~A() to be called in this program, but it isn't:

#include <iostream>

struct A {
  ~A() { std::cout << "~A()" << std::endl; }
};

void f() {
  A a;
  throw "spam";
}

int main() { f(); }

However, if I change last line to

int main() try { f(); } catch (...) { throw; }

then A::~A() is called.

I am compiling with "Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 14.00.50727.762 for 80x86" from Visual Studio 2005. Command line is cl /EHa my.cpp.

Is compiler right as usual? What does standard say on this matter?


The destructor is not being called because terminate() for the unhandled exception is called before the stack gets unwound.

The specific details of what the C++ spec says is outside of my knowledge, but a debug trace with gdb and g++ seems to bear this out.

According to the draft standard section 15.3 bullet 9:

9 If no matching handler is found in a program, the function terminate()
  (_except.terminate_)  is  called.  Whether or not the stack is unwound
  before calling terminate() is implementation-defined.

C++ language specification states: The process of calling destructors for automatic objects constructed on the path from a try block to a throw-expression is called “stack unwinding.” Your original code does not contain try block, that is why stack unwinding does not happen.