我刚刚开始使用 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 的全部基础吗?
非常感谢指点和更正!