c++ - 异常c++中的堆栈展开

标签 c++ exception try-catch stack-unwinding

我开始学习 C++ 中的异常主题。 我遇到了术语“堆栈展开”,据我所知,这意味着, 每当抛出异常,并且“抛出函数”中没有 catch block 时,函数堆栈将“展开”,并且所有本地对象的 d'tor 都将被调用(同样的事情也会发生在外部函数中直到遇到合适的 catch block )。

我的问题:

假设异常是在 try block 中抛出的,并有合适的后续捕获, 是否会为 try block 内定义的所有对象调用 d'tor? 或者在异常发生之前对 try block 中定义的所有对象?或者根本没有对象,他们将“等待”函数退出?

最佳答案

语义是当控件离开 block 时,在 block 中声明的任何局部变量都应该被销毁(函数是一个命名 block ,其参数是局部变量)。因此,当您离开 try-block 时,任何本地创建的变量都将被销毁并调用其适当的 dtor。所造之物皆灭,若非所造,则不能灭。唯一没有被销毁的是异常对象本身,如果它被抛出(当然)。

来自 C++ 规范:

15.2 Constructors and destructors 1. As control passes from the point where an exception is thrown to a handler, destructors are invoked for all automatic objects constructed since the try block was entered. The automatic objects are destroyed in the reverse order of the completion of their construction

15.2 Constructors and destructors 3. The process of calling destructors for automatic objects constructed on the path from a try block to the point where an exception is thrown is called “stack unwinding.”

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

相关文章:

c++ - 过载 ">>"如何操作?

c++ - 如何在 C++ 中使用/访问类的内部友元函数?

c++ - 更改数据时 UB 的说明

c++ - 抛出异常时使用 cout 语句尝试阻止行为

C++ throw 类成员

java - 尝试捕捉数字输入

c++ - 如果应用程序以管理员身份运行,则奇怪的文件权限

ASP.NET 自定义错误页面 - Server.GetLastError() 为 null

php - 如何 try catch 并继续php中的脚本

swift - 使用错误枚举的关联值和计算属性