C++ RAII not working?

c++, exception, raii

Solution

You don't have a handler for your exception. When this happens the standard says that std::terminate is called, which in turn calls abort. See section 14.7 in The C++ Programming Language, 3rd edition.

Problem

I'm just getting started with RAII in C++ and set up a little test case. Either my code is deeply confused, or RAII is not working! (I guess it is the former). If I run: ``` #include <exception> #include <iostream> class A { public: A(int i) { i_ = i; std::cout << "A " << i_ << " constructed" << std::endl; } ~A() { std::cout << "A " << i_ << " destructed" << std::endl; } private: int i_; }; int main(void) { A a1(1); A a2(2); throw std::exception(); return 0; } ``` with the exception commented out I get: ``` A 1 constructed A 2 constructed A 2 destructed A 1 destructed ``` as expected, but with the exception I get: ``` A 1 constructed A 2 constructed terminate called after throwing an instance of 'std::exception' what(): std::exception Aborted ``` so my objects aren't destructed even though they are going out of scope. Is this not the whole basis for RAII. Pointers and corrections much appreciated!

Original source