在析构函数中抛出异常 - 有什么缺点?

时间:2014-01-24 13:29:04

标签: c++

在析构函数中抛出异常有什么缺点?

目前我能看到的唯一不利因素是它可能会停止释放资源,还有其他缺点吗?

1 个答案:

答案 0 :(得分:6)

如果由于展开堆栈以处理另一个异常而调用析构函数,那么throw将终止程序 - 一次不能有多个未处理的异常。

如果数组元素的析构函数抛出,则不会调用其余元素的析构函数。这可能会导致内存泄漏和其他不良。

投掷析构函数使得提供异常保证变得困难或不可能。例如,用于实现带有强异常保证的赋值的“复制和交换”习惯用法(即保证,如果抛出异常,没有任何改变)将失败:

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;
}