catch中后面的append()会不会导致rethrow的异常看到append()被调用的效果?
try {
mayThrowMyErr();
} catch (myErr &err) {
err.append("Add to my message here");
throw; // Does the rethrow exception reflect the call to append()?
}
同样,如果我这样重写,如果实际异常是由 myErr 派生的,是否会发生位切片?
try {
mayThrowObjectDerivedFromMyErr();
} catch (myErr &err) {
err.append("Add to my message's base class here");
throw err; // Do I lose the derived class exception and only get myErr?
}
原文由 WilliamKF 发布,翻译遵循 CC BY-SA 4.0 许可协议
在这两种情况下,由于您通过引用捕获,因此您实际上是在更改原始异常对象的状态(您可以将其视为驻留在 一个神奇的内存位置,该位置将在随后的展开期间保持有效
0x98e7058
在下面的示例中)。然而,throw;
throw err;
,通过您的修改,保留原始异常对象,在0x98e7058
的“神奇位置”中---
) 将 反映对 append() 的调用err
的 副本,然后重新抛出(在不同的“神奇位置”0x98e70b0
因为所有编译器都知道err
could be an object on the stack about to be unwinded, likee
was at0xbfbce430
, not in the “magical location” at0x98e7058
),因此在基类实例的复制构造过程中, 您将丢失派生类特定的数据。简单的程序来说明正在发生的事情:
结果:
另见: