gpt4 book ai didi

c++ - 析构函数抛出异常

转载 作者:行者123 更新时间:2023-11-27 22:57:55 26 4
gpt4 key购买 nike

我正在阅读 Scott Meyerses C++,现在我在析构函数抛出异常部分。这是他说的:

When the vector v is destroyed, it is responsible for destroying all the Widgets it contains. Suppose v has ten Widgets in it, and during destruction of the first one, an exception is thrown. The other nine Widgets still have to be destroyed (otherwise any resources they hold would be leaked), so v should invoke their destructors. But suppose that during those calls, a second Widget destructor throws an exception. Now there are two simultaneously active exceptions

因此,据我所知,如果 vector 的第一个元素抛出异常,并不意味着程序会在之后立即终止。该实现尝试销毁 vector 中的其他对象。让我举个例子:

#include<iostream>
#include<vector>

struct A
{
~A(){ std::cout << "destruction" << std::endl; throw std::exception(); }
};

int main()
{
A a[] = {A(), A(), A(), A(), A(), A()};
std::vector<A> v;
v.assign(a, a+6);
}

DEMO

程序在第一次异常抛出后立即终止。 promise 的第二个异常抛出在哪里?

最佳答案

如果标准库组件调用的析构函数通过异常退出,则行为未定义。 [res.on.functions]/p2,强调我的:

In particular, the effects are undefined in the following cases:

  • [...]
  • if any replacement function or handler function or destructor operation exits via an exception, unless specifically allowed in the applicable Required behavior: paragraph.
  • [...]

关于c++ - 析构函数抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30771765/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com