Files
ternfs-XTXMarkets/cpp/core/ScopeGuard.hpp
Francesco Mazzoli 9adca070ba Convert build system to cmake
Also, produce fully static binaries. This means that `gethostname`
does not work (doesn't work with static glibc unless you build it
with `--enable-static-nss`, which no distro builds glibc with).
2023-01-26 23:20:58 +00:00

46 lines
979 B
C++

#pragma once
#include "Common.hpp"
#define ON_BLOCK_EXIT_INNER(line) SCOPEGUARD ## line
#define ON_BLOCK_EXIT UNUSED const auto & ON_BLOCK_EXIT_INNER(__LINE__) = makeScopeGuard
template<typename L>
class ScopeGuard {
public:
explicit ScopeGuard(L &&l) :
_committed(false),
_rollback(std::forward<L>(l)) {
}
// This is important, the class can be moved, this means
// we can return by value and even if the copy is not elided
// then we will only execute the commit once.
ScopeGuard(ScopeGuard &&rhs) :
_committed(rhs._committed),
_rollback(std::move(rhs._rollback)) {
rhs._committed = true;
}
~ScopeGuard() {
if (!_committed) {
_rollback();
}
}
void commit() noexcept {
_committed = true;
}
private:
bool _committed;
L _rollback;
};
template<typename L>
ScopeGuard<L> makeScopeGuard(L &&r) {
return ScopeGuard<L>(std::forward<L>(r));
}