2014-01-24 53 views
0

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

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

+3

将异常另一个异常处于活动状态(未捕获)导致程序立即终止。 –

+1

举个例子,你认为这是一个好主意 – Rob

+0

@Rob我不认为这是一个好主意,但我不明白为什么它不是,这就是为什么我问。小丑有一个好点 –

回答

6

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

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

投掷析构器使得难以或不可能提供异常保证。例如,用于执行具有强大例外保证(即保证如果抛出异常,没有任何变化)的“复制和交换”成语将失败:

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; 
} 
相关问题