【问题标题】:Exception Guard Idiom in Boost::Math::QuaternionBoost::Math::Quaternion 中的异常保护习语
【发布时间】:2014-03-28 16:06:54
【问题描述】:

boost::math::quaternion 的实现(您可以浏览它here)广泛使用注释为// exception guard 的成语。例如:

template<typename X>
quaternion<T> &        operator += (quaternion<X> const & rhs)
{
    T    at = a + static_cast<T>(rhs.R_component_1());    // exception guard
    T    bt = b + static_cast<T>(rhs.R_component_2());    // exception guard
    T    ct = c + static_cast<T>(rhs.R_component_3());    // exception guard
    T    dt = d + static_cast<T>(rhs.R_component_4());    // exception guard

    a = at;
    b = bt;
    c = ct;
    d = dt;

    return(*this);
}

// exception guard 在这种情况下是什么意思?

【问题讨论】:

    标签: c++ boost idioms


    【解决方案1】:

    我想这都是关于static_cast 转换的,它告诉编译器在编译时执行几个类型转换检查,从而“保护”你的程序不会因为 四元数而在运行时抛出异常 模板类滥用。

    【讨论】:

      【解决方案2】:

      如果你正在阅读这段代码,你应该对自己说“到底为什么要做这些疯狂的临时工,而不是仅仅做

      a += static_cast<T>(rhs.R_component_1());
      b += static_cast<T>(rhs.R_component_2());
      c += static_cast<T>(rhs.R_component_3());
      d += static_cast<T>(rhs.R_component_4());
      

      然后就完成了吗?”

      cmets 将回答您的问题:临时变量在那里,因此如果任何操作引发异常,四元数不会被部分修改。 IE,加法赋值应该是原子的。

      【讨论】:

      • 终于!一个有道理的答案!谢谢。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-05-24
      • 2016-06-17
      • 1970-01-01
      • 1970-01-01
      • 2018-10-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多