diff --git a/include/cpputils/scope_guard.h b/include/cpputils/scope_guard.h new file mode 100644 index 0000000..6684d8a --- /dev/null +++ b/include/cpputils/scope_guard.h @@ -0,0 +1,40 @@ +#pragma once +#include + +namespace cpputils { +namespace scope_guard { + +template +class scope_guard { + public: + explicit scope_guard(F&& f) noexcept + : func(std::forward(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 +scope_guard make_scope_guard(F&& f) noexcept { + return scope_guard(std::forward(f)); +} + +} // namespace scope_guard +} // namespace cpputils