c++ - RAII 和堆栈展开

标签 c++ exception raii stack-unwinding

直到我关于 RAII 和堆栈展开的“相互缠绕”(因为缺少更好的词)的概念是/是相当(如果不是完全)错误的。我的理解是,使用 RAII 可以防止任何/所有资源泄漏——甚至可能由未处理的异常引起的泄漏。

但是写this test program随后偶然发现 this article/documentation ,让我意识到堆栈展开只会导致启用 RAII 的资源重新分配在 try block 内开始自动执行,而不是在外部/其他范围内自动执行。

我对这个(新)理解是否正确?还是我还没有掌握更多的细微差别?那里的任何专家都想插话吗?指向任何好的文章/分析/解释(堆栈展开)的指针将是有帮助的/值得赞赏的......

最佳答案

来自 C++03 标准,§15.3/9:

If no matching handler is found in a program, the function terminate() is called; whether or not the stack is unwound before this call to terminate() is implementation-defined (15.5.1).

§15.5.1/1:

In the following situations exception handling must be abandoned for less subtle error handling techniques: ... when the exception handling mechanism cannot find a handler for a thrown exception (15.3) ...

§15.5.1/2:

In such cases,

    void terminate();

is called (18.6.3). In the situation where no matching handler is found, it is implementation-defined whether or not the stack is unwound before terminate() is called. In all other situations, the stack shall not be unwound before terminate() is called. An implementation is not permitted to finish stack unwinding prematurely based on a determination that the unwind process will eventually cause a call to terminate().

关于c++ - RAII 和堆栈展开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5557555/

相关文章:

c++ - OpenCL 缓冲区分配和映射最佳实践

c++ - 在 C++ 中抛出后会调用析构函数吗?

c++ - 将静态 const 成员重新声明为 constexpr 是否会自动将其限定为内联?

c++ - 将 std::find() 与反向迭代器一起使用

c# - 无法加载系统数据

c# - 更好地处理连接到互联网的方法中发生的异常

c++ - 在异常对象上调用 std::move 是否正确?

c++ - 范围互斥锁的自定义 RAII C++ 实现

c++ - 优化在网格图中查找哈密顿循环的函数?

exception - 使用线程池时出现 Hadoop 'Filesystem closed' 异常