Boost :: Math :: Quaternion中的异常守卫成语

时间:2014-02-26 03:23:18

标签: c++ boost idioms

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是什么意思?

2 个答案:

答案 0 :(得分: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());

并完成它?“

评论是回答你的问题:暂时性存在,以便如果任何操作抛出异常,则四元数不会被部分修改。 IE,添加分配应该是原子的。

答案 1 :(得分:0)

我认为这完全是static_cast转换,它告诉编译器在编译时执行多个类型转换检查,从而“防止”程序在运行时因为四元数模板类滥用。