Chapter 40. Sentries

#include <x/sentry.H>

void transaction(const DBH &dbh)
{
    auto transaction_sentry=x::make_sentry(
        [&]
        {
            dbh->rollback();
        }
    );

    dbh->begin();
    transaction_sentry.guard();

    // ...

    dbh->commit();
    transaction_sentry.unguard();
}

x::make_sentry implements an ad-hoc RAII design pattern using a lambda. x::make_sentry() returns an object that should exist on the stack. If the object goes out of scope after guard() and before unguard(), the object's destructor invokes the lambda.

In the example above, an exception that gets thrown any time after the begin(), and before the commit(), results in the rollback() getting automatically invoked.

Note

The lambda should not throw exceptions, although a thrown x::exception is going to get caught, and logged.