[Common] add scope out macro for easy releasing
authorpius.lee <pius.lee@samsung.com>
Fri, 16 Jan 2015 05:26:11 +0000 (14:26 +0900)
committerpius.lee <pius.lee@samsung.com>
Fri, 16 Jan 2015 06:11:56 +0000 (15:11 +0900)
Change-Id: I5181036cc35c4cd78b9863254905f8ea73abe9ee
Signed-off-by: pius.lee <pius.lee@samsung.com>
src/common/scope_exit.h

index e2ad9736e17654185d946cf5715d6138466595ca..9de2192833d09588e6270156808d8adbfa15ae65 100644 (file)
@@ -72,6 +72,40 @@ ScopeExit<F> MakeScopeExit(F f) {
   return ScopeExit<F>(f);
 }
 
+// Internal use for macro SCOPE_EXIT
+template <typename F>
+ScopeExit<typename std::decay<F>::type>
+operator+(int, F&& f)
+{
+  return ScopeExit<typename std::decay<F>::type>
+  {std::forward<F>(f)};
+}
+
+/*
+ * This macro is for simple way to using ScopeExit
+ *
+ * Example:
+ *
+ *   struct unit;
+ *   struct unit* unit_new();
+ *   void unit_free(unit*);
+ *
+ *   void ExampleFunctionScope() {
+ *     struct unit* u = unit_new();
+ *
+ *     // automatic cleanup for all cases
+ *     SCOPE_EXIT {
+ *       unit_free(u);
+ *     };
+ *
+ *     // do 1st operation with unit and possibly quit function
+ *     // do 2nd operation with unit and possibly quit function
+ *     // do 3rd operation with unit and possibly quit function
+ *   }
+ */
+#define SCOPE_EXIT \
+    auto SCOPE_EXIT_##__LINE__ = 0 + [&]() noexcept
+
 }  // namespace common
 
 #endif  // COMMON_SCOPE_EXIT_H_