Question

Given Jon Kalb's strongly exception-safe code to solve the Cargill Widget example, what prevents the compiler from re-organizing the operations and thus making the code not strongly exception-safe?

#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;
};

Is it the "the compiler can't change the observable behaviour" rule?

Reference:

Was it helpful?

Solution

You said it yourself: the compiler cannot do anything which might modify observable behavior. And it is obliged to take possible exceptions into account. Potentially, the restrictions on reordering because of this could have a significant negative impact on optimization. Practically, there are two cases to consider: the compiler doesn't know what goes on in the functions being called, and so can't reorder accross them, or the compiler does have the ability to optimize accross translation units, in which case, it will usually be able to determine that the function won't throw (assuming it won't), and thus reorder exactly as if it ignored exceptions. Or not reorder, if throwing an exception might cause a change in the observable behavior if it did.

OTHER TIPS

any optimization has to preserve the provable properties of the code. otherwise any code could be replaced with a program that did nothing and was maximally fast. effects of exceptions are part of provable properties.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top