summaryrefslogtreecommitdiff
path: root/zen/scope_guard.h
diff options
context:
space:
mode:
authorDaniel Wilhelm <daniel@wili.li>2014-04-18 17:15:16 +0200
committerDaniel Wilhelm <daniel@wili.li>2014-04-18 17:15:16 +0200
commitbd6336c629841c6db3a6ca53a936d629d34db53b (patch)
tree3721ef997864108df175ce677a8a7d4342a6f1d2 /zen/scope_guard.h
parent4.0 (diff)
downloadFreeFileSync-bd6336c629841c6db3a6ca53a936d629d34db53b.tar.gz
FreeFileSync-bd6336c629841c6db3a6ca53a936d629d34db53b.tar.bz2
FreeFileSync-bd6336c629841c6db3a6ca53a936d629d34db53b.zip
4.1
Diffstat (limited to 'zen/scope_guard.h')
-rw-r--r--zen/scope_guard.h77
1 files changed, 77 insertions, 0 deletions
diff --git a/zen/scope_guard.h b/zen/scope_guard.h
new file mode 100644
index 00000000..d3633284
--- /dev/null
+++ b/zen/scope_guard.h
@@ -0,0 +1,77 @@
+// **************************************************************************
+// * This file is part of the zenXML project. It is distributed under the *
+// * Boost Software License, Version 1.0. See accompanying file *
+// * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt. *
+// * Copyright (C) 2011 ZenJu (zhnmju123 AT gmx.de) *
+// **************************************************************************
+
+#ifndef ZEN_SCOPEGUARD_8971632487321434
+#define ZEN_SCOPEGUARD_8971632487321434
+
+//best of Zen, Loki and C++11
+
+namespace zen
+{
+//Scope Guard
+/*
+ zen::ScopeGuard lockAio = zen::makeGuard([&]() { ::CancelIo(hDir); });
+ ...
+ lockAio.dismiss();
+*/
+
+//Scope Exit
+/*
+ ZEN_ON_BLOCK_EXIT(::CloseHandle(hDir));
+*/
+
+class ScopeGuardBase
+{
+public:
+ void dismiss() const { dismissed_ = true; }
+
+protected:
+ ScopeGuardBase() : dismissed_(false) {}
+ ScopeGuardBase(const ScopeGuardBase& other) : dismissed_(other.dismissed_) { other.dismissed_ = true; } //take over responsibility
+ ~ScopeGuardBase() {}
+
+ bool isDismissed() const { return dismissed_; }
+
+private:
+ ScopeGuardBase& operator=(const ScopeGuardBase&); // = delete;
+
+ mutable bool dismissed_;
+};
+
+
+template <typename F>
+class ScopeGuardImpl : public ScopeGuardBase
+{
+public:
+ ScopeGuardImpl(F fun) : fun_(fun) {}
+
+ ~ScopeGuardImpl()
+ {
+ if (!this->isDismissed())
+ try
+ {
+ fun_();
+ }
+ catch (...) {}
+ }
+
+private:
+ F fun_;
+};
+
+typedef const ScopeGuardBase& ScopeGuard;
+
+template <class F> inline
+ScopeGuardImpl<F> makeGuard(F fun) { return ScopeGuardImpl<F>(fun); }
+}
+
+#define ZEN_CONCAT_SUB(X, Y) X ## Y
+#define ZEN_CONCAT(X, Y) ZEN_CONCAT_SUB(X, Y)
+
+#define ZEN_ON_BLOCK_EXIT(X) zen::ScopeGuard ZEN_CONCAT(dummy, __LINE__) = zen::makeGuard([&](){X;}); (void)ZEN_CONCAT(dummy, __LINE__);
+
+#endif //ZEN_SCOPEGUARD_8971632487321434
bgstack15