fix a multiline comment warning
[folly.git] / folly / ScopeGuard.h
1 /*
2  * Copyright 2011-present Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #pragma once
18
19 #include <cstddef>
20 #include <functional>
21 #include <new>
22 #include <type_traits>
23 #include <utility>
24
25 #include <folly/Portability.h>
26 #include <folly/Preprocessor.h>
27 #include <folly/UncaughtExceptions.h>
28
29 namespace folly {
30
31 namespace detail {
32
33 class ScopeGuardImplBase {
34  public:
35   void dismiss() noexcept {
36     dismissed_ = true;
37   }
38
39   template <typename T>
40   FOLLY_ALWAYS_INLINE static void runAndWarnAboutToCrashOnException(
41       T& function) noexcept {
42     try {
43       function();
44     } catch (...) {
45       warnAboutToCrash();
46       std::terminate();
47     }
48   }
49
50  protected:
51   ScopeGuardImplBase() noexcept : dismissed_(false) {}
52
53   static ScopeGuardImplBase makeEmptyScopeGuard() noexcept {
54     return ScopeGuardImplBase{};
55   }
56
57   template <typename T>
58   static const T& asConst(const T& t) noexcept {
59     return t;
60   }
61
62   bool dismissed_;
63
64  private:
65   static void warnAboutToCrash() noexcept;
66 };
67
68 template <typename FunctionType>
69 class ScopeGuardImpl : public ScopeGuardImplBase {
70  public:
71   explicit ScopeGuardImpl(FunctionType& fn) noexcept(
72       std::is_nothrow_copy_constructible<FunctionType>::value)
73       : ScopeGuardImpl(
74             asConst(fn),
75             makeFailsafe(std::is_nothrow_copy_constructible<FunctionType>{},
76                          &fn)) {}
77
78   explicit ScopeGuardImpl(const FunctionType& fn) noexcept(
79       std::is_nothrow_copy_constructible<FunctionType>::value)
80       : ScopeGuardImpl(
81             fn,
82             makeFailsafe(std::is_nothrow_copy_constructible<FunctionType>{},
83                          &fn)) {}
84
85   explicit ScopeGuardImpl(FunctionType&& fn) noexcept(
86       std::is_nothrow_move_constructible<FunctionType>::value)
87       : ScopeGuardImpl(
88             std::move_if_noexcept(fn),
89             makeFailsafe(std::is_nothrow_move_constructible<FunctionType>{},
90                          &fn)) {}
91
92   ScopeGuardImpl(ScopeGuardImpl&& other) noexcept(
93       std::is_nothrow_move_constructible<FunctionType>::value)
94       : function_(std::move_if_noexcept(other.function_)) {
95     // If the above line attempts a copy and the copy throws, other is
96     // left owning the cleanup action and will execute it (or not) depending
97     // on the value of other.dismissed_. The following lines only execute
98     // if the move/copy succeeded, in which case *this assumes ownership of
99     // the cleanup action and dismisses other.
100     dismissed_ = other.dismissed_;
101     other.dismissed_ = true;
102   }
103
104   ~ScopeGuardImpl() noexcept {
105     if (!dismissed_) {
106       execute();
107     }
108   }
109
110  private:
111   static ScopeGuardImplBase makeFailsafe(std::true_type, const void*) noexcept {
112     return makeEmptyScopeGuard();
113   }
114
115   template <typename Fn>
116   static auto makeFailsafe(std::false_type, Fn* fn) noexcept
117       -> ScopeGuardImpl<decltype(std::ref(*fn))> {
118     return ScopeGuardImpl<decltype(std::ref(*fn))>{std::ref(*fn)};
119   }
120
121   template <typename Fn>
122   explicit ScopeGuardImpl(Fn&& fn, ScopeGuardImplBase&& failsafe)
123       : ScopeGuardImplBase{}, function_(std::forward<Fn>(fn)) {
124     failsafe.dismiss();
125   }
126
127   void* operator new(std::size_t) = delete;
128
129   void execute() noexcept {
130     runAndWarnAboutToCrashOnException(function_);
131   }
132
133   FunctionType function_;
134 };
135
136 template <typename F>
137 using ScopeGuardImplDecay = ScopeGuardImpl<typename std::decay<F>::type>;
138
139 } // namespace detail
140
141 /**
142  * ScopeGuard is a general implementation of the "Initialization is
143  * Resource Acquisition" idiom.  Basically, it guarantees that a function
144  * is executed upon leaving the currrent scope unless otherwise told.
145  *
146  * The makeGuard() function is used to create a new ScopeGuard object.
147  * It can be instantiated with a lambda function, a std::function<void()>,
148  * a functor, or a void(*)() function pointer.
149  *
150  *
151  * Usage example: Add a friend to memory if and only if it is also added
152  * to the db.
153  *
154  * void User::addFriend(User& newFriend) {
155  *   // add the friend to memory
156  *   friends_.push_back(&newFriend);
157  *
158  *   // If the db insertion that follows fails, we should
159  *   // remove it from memory.
160  *   auto guard = makeGuard([&] { friends_.pop_back(); });
161  *
162  *   // this will throw an exception upon error, which
163  *   // makes the ScopeGuard execute UserCont::pop_back()
164  *   // once the Guard's destructor is called.
165  *   db_->addFriend(GetName(), newFriend.GetName());
166  *
167  *   // an exception was not thrown, so don't execute
168  *   // the Guard.
169  *   guard.dismiss();
170  * }
171  *
172  * Examine ScopeGuardTest.cpp for some more sample usage.
173  *
174  * Stolen from:
175  *   Andrei's and Petru Marginean's CUJ article:
176  *     http://drdobbs.com/184403758
177  *   and the loki library:
178  *     http://loki-lib.sourceforge.net/index.php?n=Idioms.ScopeGuardPointer
179  *   and triendl.kj article:
180  *     http://www.codeproject.com/KB/cpp/scope_guard.aspx
181  */
182 template <typename F>
183 detail::ScopeGuardImplDecay<F> makeGuard(F&& f) noexcept(
184     noexcept(detail::ScopeGuardImplDecay<F>(static_cast<F&&>(f)))) {
185   return detail::ScopeGuardImplDecay<F>(static_cast<F&&>(f));
186 }
187
188 namespace detail {
189
190 #if defined(FOLLY_EXCEPTION_COUNT_USE_CXA_GET_GLOBALS) || \
191     defined(FOLLY_EXCEPTION_COUNT_USE_GETPTD) ||          \
192     defined(FOLLY_EXCEPTION_COUNT_USE_STD)
193
194 /**
195  * ScopeGuard used for executing a function when leaving the current scope
196  * depending on the presence of a new uncaught exception.
197  *
198  * If the executeOnException template parameter is true, the function is
199  * executed if a new uncaught exception is present at the end of the scope.
200  * If the parameter is false, then the function is executed if no new uncaught
201  * exceptions are present at the end of the scope.
202  *
203  * Used to implement SCOPE_FAIL and SCOPE_SUCCESS below.
204  */
205 template <typename FunctionType, bool ExecuteOnException>
206 class ScopeGuardForNewException {
207  public:
208   explicit ScopeGuardForNewException(const FunctionType& fn) : function_(fn) {}
209
210   explicit ScopeGuardForNewException(FunctionType&& fn)
211       : function_(std::move(fn)) {}
212
213   ScopeGuardForNewException(ScopeGuardForNewException&& other) = default;
214
215   ~ScopeGuardForNewException() noexcept(ExecuteOnException) {
216     if (ExecuteOnException == (exceptionCounter_ < uncaught_exceptions())) {
217       if (ExecuteOnException) {
218         ScopeGuardImplBase::runAndWarnAboutToCrashOnException(function_);
219       } else {
220         function_();
221       }
222     }
223   }
224
225  private:
226   ScopeGuardForNewException(const ScopeGuardForNewException& other) = delete;
227
228   void* operator new(std::size_t) = delete;
229
230   FunctionType function_;
231   int exceptionCounter_{uncaught_exceptions()};
232 };
233
234 /**
235  * Internal use for the macro SCOPE_FAIL below
236  */
237 enum class ScopeGuardOnFail {};
238
239 template <typename FunctionType>
240 ScopeGuardForNewException<typename std::decay<FunctionType>::type, true>
241 operator+(detail::ScopeGuardOnFail, FunctionType&& fn) {
242   return
243       ScopeGuardForNewException<typename std::decay<FunctionType>::type, true>(
244       std::forward<FunctionType>(fn));
245 }
246
247 /**
248  * Internal use for the macro SCOPE_SUCCESS below
249  */
250 enum class ScopeGuardOnSuccess {};
251
252 template <typename FunctionType>
253 ScopeGuardForNewException<typename std::decay<FunctionType>::type, false>
254 operator+(ScopeGuardOnSuccess, FunctionType&& fn) {
255   return
256       ScopeGuardForNewException<typename std::decay<FunctionType>::type, false>(
257       std::forward<FunctionType>(fn));
258 }
259
260 #endif // native uncaught_exception() supported
261
262 /**
263  * Internal use for the macro SCOPE_EXIT below
264  */
265 enum class ScopeGuardOnExit {};
266
267 template <typename FunctionType>
268 ScopeGuardImpl<typename std::decay<FunctionType>::type>
269 operator+(detail::ScopeGuardOnExit, FunctionType&& fn) {
270   return ScopeGuardImpl<typename std::decay<FunctionType>::type>(
271       std::forward<FunctionType>(fn));
272 }
273 } // namespace detail
274
275 } // namespace folly
276
277 #define SCOPE_EXIT \
278   auto FB_ANONYMOUS_VARIABLE(SCOPE_EXIT_STATE) \
279   = ::folly::detail::ScopeGuardOnExit() + [&]() noexcept
280
281 #if defined(FOLLY_EXCEPTION_COUNT_USE_CXA_GET_GLOBALS) || \
282     defined(FOLLY_EXCEPTION_COUNT_USE_GETPTD) ||          \
283     defined(FOLLY_EXCEPTION_COUNT_USE_STD)
284 #define SCOPE_FAIL \
285   auto FB_ANONYMOUS_VARIABLE(SCOPE_FAIL_STATE) \
286   = ::folly::detail::ScopeGuardOnFail() + [&]() noexcept
287
288 #define SCOPE_SUCCESS \
289   auto FB_ANONYMOUS_VARIABLE(SCOPE_SUCCESS_STATE) \
290   = ::folly::detail::ScopeGuardOnSuccess() + [&]()
291 #endif // native uncaught_exception() supported