gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 15:42:12 25 4
gpt4 key购买 nike

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

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

最佳答案

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

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

抛出析构函数使得提供异常保证变得困难或不可能。例如,用于实现具有强异常保证(即保证,如果抛出异常,则没有任何更改)的赋值的“ copy-and-swap ”习语将失败:

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

关于c++ - 在析构函数中抛出异常——有什么缺点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21333989/

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