C++ 中抛出后是否调用析构函数?
我运行了一个示例程序,确实调用了堆栈分配对象的析构函数,但这是否由标准保证?
I ran a sample program and indeed destructors for stack-allocated objects are called, but is this guaranteed by the standard?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,这是有保证的(前提是捕获了异常),具体取决于调用析构函数的顺序:
此外,如果在对象构造期间抛出异常,则保证部分构造的对象的子对象被正确销毁:
整个过程称为“堆栈展开”:
堆栈展开构成了广泛使用的技术的基础,该技术称为资源获取即初始化(RAII)。
请注意,如果未捕获异常,则不一定完成堆栈展开。在这种情况下,是否完成堆栈展开取决于实现。但无论堆栈展开是否完成,在这种情况下,您都可以保证最终调用
std::terminate
。Yes, it is guaranteed (provided the exception is caught), down to the order in which the destructors are invoked:
Furthermore, if the exception is thrown during object construction, the subobjects of the partially-constructed object are guaranteed to be correctly destroyed:
This whole process is known as "stack unwinding":
Stack unwinding forms the basis of the widely-used technique called Resource Acquisition Is Initialization (RAII).
Note that stack unwinding is not necessarily done if the exception is not caught. In this case it's up to the implementation whether stack unwinding is done. But whether stack unwinding is done or not, in this case you're guaranteed a final call to
std::terminate
.是的,保证在堆栈展开时调用析构函数,包括由于抛出异常而展开。您只需记住几个有关异常的技巧:
Yes, destructors are guaranteed to be called on stack unwinding, including unwinding due to exception being thrown. There are only few tricks with exceptions that you have to remember:
如果抛出异常,则 cpp 操作通常会继续。这包括析构函数和堆栈弹出。但是,如果未捕获异常,则无法保证堆栈弹出。
我的移动编译器也无法捕获裸露抛出或空抛出。
例子:
If a throw is caught then normally cpp operations continue. This include destructors and stack popping. However if the exception is not caught, stack popping is not guaranteed.
Also a bare throw or empty throw cannot be caught by my mobile compiler.
example: