Last active
May 11, 2016 03:02
-
-
Save mrts/5890888 to your computer and use it in GitHub Desktop.
C++11 scope guard, based on https://skydrive.live.com/view.aspx?resid=F1B8FF18A2AEC5C5!1158&app=WordPdf&authkey=!APo6bfP5sJ8EmH4
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
#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; | |
} |
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
#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