Created
May 11, 2019 20:10
-
-
Save mrange/dd3230404dee5e7f5da80de3d33a92fa to your computer and use it in GitHub Desktop.
on_exit - useful with C Apis
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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