Bana
Bana

Reputation: 117

Exception safety in C++ code

struct CImpl {
    A a;
    B b;
};

class C {
    unique_ptr<CImpl> pImpl;
    ...
    void f() {
        auto temp = make_unique<CImpl> (*pImpl);
        temp->a.method1();
        temp->b.method2();
        std::swap(pImpl, temp); // no throw
    }
};

Consider this example above; we are dealing with exceptions

(1)Now consider that a.method1(), b.method2() are both no-throw.

In this case does f offer a no-throw guarantee? I think yes.

(2)Now consider that a.method1(), b.method2() are both strong guarantee (if exception thrown, its as if nothing happened). Then in this case, we can guarantee f is strong because we are using temporaries so if exception occurs, C remains untouched.

Is this right? All this also follows because std::swap(**, **) is no-throw.

Upvotes: 0

Views: 313

Answers (1)

user0042
user0042

Reputation: 8018

There's no guarantee that this line won't throw an exception:

auto temp = make_unique<CImpl> (*pImpl);

All of the involved copy constructors there could throw. So no f() isn't strongly exception safe.

Upvotes: 3

Related Questions