feat: add scope_guard
This commit is contained in:
40
include/cpputils/scope_guard.h
Normal file
40
include/cpputils/scope_guard.h
Normal 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
|
||||
Reference in New Issue
Block a user