C ++ RAII nie działa?
Po prostu zaczynam pracę z RAII w C ++ i ustawiam mały przypadek testowy. Albo mój kod jest głęboko zdezorientowany, albo RAII nie działa! (Myślę, że to pierwszy).
Jeśli biegnę:
#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;
}
z wyjątkiem skomentowany otrzymuję:
A 1 constructed
A 2 constructed
A 2 destructed
A 1 destructed
zgodnie z oczekiwaniami, ale z wyjątkiem:
A 1 constructed
A 2 constructed
terminate called after throwing an instance of 'std::exception'
what(): std::exception
Aborted
więc moje obiekty nie są niszczone, nawet jeśli wychodzą poza zasięg. Czy to nie jest cała podstawa RAII.
Bardzo cenione wskaźniki i poprawki!