Skip to content

Instantly share code, notes, and snippets.

@codebrainz
Last active August 29, 2015 14:12
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 codebrainz/70025dc52b7c4d156c05 to your computer and use it in GitHub Desktop.
Save codebrainz/70025dc52b7c4d156c05 to your computer and use it in GitHub Desktop.
A macro/template implementation of C++ scope guard
#pragma once
#include <utility>
namespace ScopeExitNamespace__ {
template<typename T> struct OnScopeExit__ {
T func;
OnScopeExit__(T func) : func(std::move(func)) {}
~OnScopeExit__() noexcept { func(); }
};
}
#define scope_exit__(id, code) \
auto scope_exit_function_##id##__ = [&](){code;}; \
ScopeExitNamespace__::OnScopeExit__<decltype(scope_exit_function_##id##__)> \
scope_exit_cleanup_##id##__(std::move(scope_exit_function_##id##__))
#define scope_exit(code) scope_exit__(__COUNTER__, code)
// #include <iostream>
// int main()
// {
// scope_exit(std::cout << "done" << std::endl);
// std::cout << "Running...";
// return 0;
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment