feat: add scope_guard

This commit is contained in:
2026-02-07 22:36:14 +01:00
parent 8e1f207b6a
commit f9b27643c9

View File

@@ -0,0 +1,40 @@
#pragma once
#include <utility>
namespace cpputils {
namespace scope_guard {
template <class F>
class scope_guard {
public:
explicit scope_guard(F&& f) noexcept
: func(std::forward<F>(f)), active(true) {}
scope_guard(scope_guard&& other) noexcept
: func(std::move(other.func)), active(other.active) {
other.dismiss();
}
scope_guard(const scope_guard&) = delete;
scope_guard& operator=(const scope_guard&) = delete;
~scope_guard() noexcept {
if (active) {
func();
}
}
void dismiss() noexcept { active = false; }
private:
F func;
bool active;
};
template <class F>
scope_guard<F> make_scope_guard(F&& f) noexcept {
return scope_guard<F>(std::forward<F>(f));
}
} // namespace scope_guard
} // namespace cpputils