以下两种代码在什么情况下不等价?
{
// some code, may throw and/or have side effects
}
try {
// same code as above
} catch(...) {
throw;
}
edit 澄清一下,我对 (i) 与上述模式的偏差(例如 catch block 中的更多代码)不感兴趣,也不 (ii) 打算邀请有关适当的光顾评论try
-catch
block 的用法。
我正在寻找有关 C++ 标准的合格答案。这个问题是由 Cheers and hth. - Alf 的评论提示的。至this answer of mine ,声明没有进一步解释上述代码不等价。
edit 他们确实是不同的。堆栈展开将在后者中完成,但不一定在前者中完成,这取决于在运行时是否找到异常处理程序(一些 catch
block 在堆栈更高的位置)。
最佳答案
后者要求堆栈展开,而在前者中,如果堆栈展开则由实现定义。
相关标准引用(均来自N3337):
[except.ctor]/1:
As control passes from a throw-expression to a handler, destructors are invoked for all automatic objects constructed since the try block was entered. The automatic objects are destroyed in the reverse order of the completion of their construction.
[except.ctor]/3:
The process of calling destructors for automatic objects constructed on the path from a try block to a throw-expression is called “stack unwinding.” [...]
[except.terminate]/2:
[When the exception handling mechanism cannot find a handler for a throw exception],std::terminate()
is called (18.8.3). In the situation where no matching handler is found, it is implementation-defined whether or not the stack is unwound beforestd::terminate()
is called. [...]
因此,如果您想保证自动对象的析构函数在未处理的异常情况下运行(例如,某些持久性存储必须在销毁时发生突变),那么 try {/*code*/} catch (...) {throw;}
会这样做,但 {/*code*/}
不会。
关于c++ - 带有 try-catch-rethrow 的代码是否等同于不带 try-catch 的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33689053/