我的问题是,如果从析构函数抛出会导致
未定义的行为,如何处理过程中发生的错误
析构函数?
主要的问题是:你不能失败到失败。失败到底意味着什么?如果将事务提交到数据库失败,并且事务未能失败(回滚失败),那么数据的完整性会发生什么变化?
由于析构函数在正常路径和异常(失败)路径上都被调用,它们本身不能失败,否则我们就是“失败”。
这是一个概念上很困难的问题,但通常解决方案是找到一种方法来确保失败不会失败。例如,数据库可能会在提交到外部数据结构或文件之前写入更改。如果事务失败,则可以丢弃文件/数据结构。它必须确保从外部结构/文件提交的更改是一个不会失败的原子事务。
务实的解决办法也许就是确保
一次又一次的失败在天文学上是不可能的,因为做东西
在某些情况下,失败几乎是不可能的。
对我来说,最合适的解决方案是以一种清理逻辑不会失败的方式编写非清理逻辑。例如,如果您想要创建一个新的数据结构来清理现有的数据结构,那么您可能会寻求提前创建那个辅助结构,这样我们就不必在析构函数中创建它了。
This is all much easier said than done, admittedly, but it's the only really proper way I see to go about it. Sometimes I think there should be an ability to write separate destructor logic for normal execution paths away from exceptional ones, since sometimes destructors feel a little bit like they have double the responsibilities by trying to handle both (an example is scope guards which require explicit dismissal; they wouldn't require this if they could differentiate exceptional destruction paths from non-exceptional ones).
Still the ultimate problem is that we can't fail to fail, and it's a hard conceptual design problem to solve perfectly in all cases. It does get easier if you don't get too wrapped up in complex control structures with tons of teeny objects interacting with each other, and instead model your designs in a slightly bulkier fashion (example: particle system with a destructor to destroy the entire particle system, not a separate non-trivial destructor per particle). When you model your designs at this kind of coarser level, you have less non-trivial destructors to deal with, and can also often afford whatever memory/processing overhead is required to make sure your destructors cannot fail.
And that's one of the easiest solutions naturally is to use destructors less often. In the particle example above, perhaps upon destroying/removing a particle, some things should be done that could fail for whatever reason. In that case, instead of invoking such logic through the particle's dtor which could be executed in an exceptional path, you could instead have it all done by the particle system when it removes a particle. Removing a particle might always be done during a non-exceptional path. If the system is destroyed, maybe it can just purge all particles and not bother with that individual particle removal logic which can fail, while the logic that can fail is only executed during the particle system's normal execution when it's removing one or more particles.
如果避免使用非平凡析构函数处理大量小对象,通常会出现这样的解决方案。当你被大量的小对象纠缠在一起时,你可能会陷入混乱,似乎不可能是异常安全的,这些小对象都有非平凡的dtor。
如果任何指定nothrow/noexcept的函数(包括应该继承其基类的noexcept规范的虚函数)试图调用任何可能抛出的函数,那么nothrow/noexcept实际上会被翻译成编译器错误,这将会有很大帮助。这样我们就能在编译时捕获所有这些东西,如果我们实际上无意中编写了一个析构函数,它可能会抛出。