C++ で RAII を使い始めたばかりで、小さなテスト ケースをセットアップしています。コードがひどく混乱しているか、RAII が機能していません! (前者だと思います。)
私が実行した場合:
#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;
}
コメントアウトされた例外を除いて、次のようになります。
A 1 constructed
A 2 constructed
A 2 destructed
A 1 destructed
予想通りですが、例外があります:
A 1 constructed
A 2 constructed
terminate called after throwing an instance of 'std::exception'
what(): std::exception
Aborted
そのため、スコープ外に出てもオブジェクトは破壊されません。これは RAII のすべての基礎ではありませんか。
ポインタと修正は大歓迎です!