C++ RAII 不工作?

标签 c++ exception raii

我刚刚开始使用 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;
}

除了注释掉的异常(exception),我得到:

A 1 constructed
A 2 constructed
A 2 destructed
A 1 destructed

正如预期的那样,但我得到的异常(exception)是:

A 1 constructed
A 2 constructed
terminate called after throwing an instance of 'std::exception'
  what():  std::exception
Aborted

所以我的对象即使超出范围也不会被破坏。这不是 RAII 的全部基础吗?

非常感谢指点和更正!

最佳答案

您的异常没有处理程序。当这种情况发生时,标准说 std::terminate 被调用,而后者又调用 abort。请参阅 The C++ Programming Language,第 3 版中的第 14.7 节。

关于C++ RAII 不工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1104136/

相关文章:

javascript - Wicked-Good-XPath 评估 xPathResult 包含 [异常 : TypeError]

c++ - C++ 最快 `finally`

c++ - 在 C++ 中模拟静态构造函数?

c++ - c++ 中 std::next_permutation() 函数的时间复杂度是多少?

c++ - 有没有简单的方法来制作可折叠的 QWidget?

c++ - 使用 WNDCLASSEX 创建窗口? [Cpp]

python - 如何获取异常列表?

c# - WCF 抛出异常

c++ - 为 RAII 模板类编写对象生成器的更好方法?

c++ - 我必须在 C++ 析构函数中收集什么垃圾