鉴于 Jon Kalb 的强异常安全代码来解决 Cargill Widget 示例,是什么阻止编译器重新组织操作,从而使代码不是强异常安全的?
#include <algorithm> // std::swap
template< typename T1, typename T2 >
class Cargill_Widget
{
public:
Cargill_Widget& operator=( Cargill_Widget const& r_other )
{
using std::swap;
T1 temp_t1( r_other.m_t1 ); // may throw
T2 temp_t2( r_other.m_t2 ); // may throw
/* The strong exception-safety line */
swap( m_t1, temp_t1 ); // no throw
swap( m_t2, temp_t2 ); // no throw
return *this;
}
private:
T1 m_t1;
T2 m_t2;
};
是否是“编译器无法更改可观察到的行为”规则?
引用:
- Jon Kalb 的“异常安全代码”演示幻灯片:http://www.exceptionsafecode.com/slides/esc.pdf
最佳答案
你自己说过:编译器不能做任何事情 可能会修改可观察到的行为。它有义务采取 考虑到可能的异常(exception)情况。潜在的限制 因此重新排序可能会产生重大负面影响 对优化的影响。实际上,有两种情况 考虑:编译器不知道在 被调用的函数,因此不能对它们重新排序,或者 编译器确实有能力优化交叉 翻译单元,在这种情况下,它通常能够 确定该函数不会抛出(假设它不会),并且 因此重新排序就好像它忽略了异常一样。或不 重新排序,如果抛出异常可能会导致 可观察到的行为。
关于c++ - 是什么阻止了编译器对强异常安全代码重新排序的优化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15554127/