Skip to content

Instantly share code, notes, and snippets.

@mrts
Last active May 11, 2016 03:02
Show Gist options
  • Save mrts/5890888 to your computer and use it in GitHub Desktop.
Save mrts/5890888 to your computer and use it in GitHub Desktop.
#include <iostream>
#include "ScopeGuard.h"
using namespace std;
void with_exception()
{
auto guard = make_guard([] { cout << "cleanup from exception" << endl; });
throw 1;
}
int main()
{
auto guard = make_guard([] { cout << "cleanup from normal exit" << endl; });
try {
with_exception();
} catch (...) {
}
return 0;
}
#ifndef SCOPEGUARD_H__
#define SCOPEGUARD_H__
#include <utility>
template <class Function>
class ScopeGuard
{
public:
ScopeGuard(Function f) :
_guardFunction(std::move(f)),
_active(true)
{ }
~ScopeGuard()
{
if (_active)
_guardFunction();
}
ScopeGuard(ScopeGuard&& rhs) :
_guardFunction(std::move(rhs._guardFunction)),
_active(rhs._active)
{
rhs.dismiss();
}
void dismiss()
{
_active = false;
}
private:
Function _guardFunction;
bool _active;
ScopeGuard() = delete;
ScopeGuard(const ScopeGuard&) = delete;
ScopeGuard& operator=(const ScopeGuard&) = delete;
};
template <class Function>
ScopeGuard<Function> make_guard(Function f)
{ return ScopeGuard<Function>(std::move(f)); }
#endif /* SCOPEGUARD_H */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment