Simplest possible header-only C++17 scope-guard library for cleanup at scope exit, which provides two tiny types:
nth::scope_exit_t
— non-dismissable guard that always runs on scope exitnth::scope_fuse_t
— dismissable guard that can be invoked or released early
Both are designed to have minimal size overhead even in debug builds to be embedded friendly.
Just copy include/nth/scope.h
into your project directly or add the library with CMake (recommended):
add_subdirectory(scope)
target_link_libraries(your_target PRIVATE scope)
target_compile_features(your_target PRIVATE cxx_std_17)
And include the header:
#include <nth/scope.h>
{
int i = 42;
nth::scope_exit_t on_exit_1 = [&] {
printf("on_exit_1: %d\n", i);
};
nth::scope_exit_t on_exit_2 = [] {
printf("on_exit_2\n");
};
nth::scope_fuse_t on_exit_3 = [] {
printf("on_exit_3\n");
};
nth::scope_fuse_t on_exit_4 = [] {
printf("on_exit_4\n");
};
on_exit_3.invoke(); // invoke before scope exit
// on_exit_3
on_exit_3.invoke(); // no-op
on_exit_3.defuse(); // no-op
on_exit_4.defuse(); // cancel before scope exit
// ~on_exit_4 won't be invoked
// ~on_exit_3 won't be invoked
// on_exit_2
// on_exit_1: 42
}