抛弃灾难的例外 - 缺点是什么

Throwing exceptions in destructors - what are the downsides?

本文关键字:缺点 是什么 抛弃      更新时间:2023-10-16

在破坏者中投掷异常的缺点是什么?

现在我唯一能看到的缺点是它可能会停止释放资源,还有其他缺点吗?

如果由于放松堆栈来处理另一个异常而被调用,则投掷将终止程序 - 您一次不能有一个未经治疗的例外。

如果阵列元素的驱动器会抛出,则将不会调用其余元素的破坏者。这可能导致内存泄漏和其他坏处。

投掷灾难使得很难或不可能提供例外保证。例如,用于实施分配的"复制和汇合"成语(即,如果抛出例外,没有任何更改的保证)将失败:

thing & thing::operator=(thing const & t) {
    // Copy the argument. If this throws, there are no side-effects.
    thing copy(t);
    // Swap with this. Must have (at least) a strong guarantee
    this->swap(copy);
    // Now the operation is complete, so nothing else must throw.
    // Destroy the copy (now the old value of "this") on return.
    // If this throws, we break the guarantee.
    return *this;
}