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!