Skip to content

Instantly share code, notes, and snippets.

@mrange
Created May 11, 2019 20:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrange/dd3230404dee5e7f5da80de3d33a92fa to your computer and use it in GitHub Desktop.
Save mrange/dd3230404dee5e7f5da80de3d33a92fa to your computer and use it in GitHub Desktop.
on_exit - useful with C Apis
#define _CRT_SECURE_NO_WARNINGS
#include <cstdio>
#include <memory>
#include <type_traits>
namespace
{
template<typename TAction>
struct scope_guard
{
scope_guard (TAction a)
: action (std::move (a))
, invoke_action (true)
{
}
~scope_guard () noexcept
{
if (invoke_action)
{
invoke_action = false;
action ();
}
}
scope_guard (scope_guard const &) = delete;
scope_guard & operator= (scope_guard const &) = delete;
scope_guard & operator= (scope_guard &&) = delete;
scope_guard (scope_guard && sg)
: action (std::move (sg.action))
, invoke_action (sg.invoke_action)
{
sg.invoke_action = false;
}
bool invoke_action ;
private:
TAction action ;
};
template<typename TAction>
auto on_exit (TAction && action)
{
return scope_guard<std::decay_t<TAction>> (std::forward<TAction> (action));
}
}
int main()
{
auto file = fopen ("hello.txt", "r");
if (file)
{
// on_exit allows us to create cleanup functions that cleanups C resources when scope closes.
// We can create "smart" pointers for all these resources but it adds a fair bit of overhead.
// I prefer on_exit for quick and not so dirty stuff
auto on_exit__close_file = on_exit ([file] { fclose (file); });
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment