2 * Copyright 2017 Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
22 #include <type_traits>
25 #include <folly/Portability.h>
26 #include <folly/Preprocessor.h>
27 #include <folly/detail/UncaughtExceptionCounter.h>
32 * ScopeGuard is a general implementation of the "Initialization is
33 * Resource Acquisition" idiom. Basically, it guarantees that a function
34 * is executed upon leaving the currrent scope unless otherwise told.
36 * The makeGuard() function is used to create a new ScopeGuard object.
37 * It can be instantiated with a lambda function, a std::function<void()>,
38 * a functor, or a void(*)() function pointer.
41 * Usage example: Add a friend to memory if and only if it is also added
44 * void User::addFriend(User& newFriend) {
45 * // add the friend to memory
46 * friends_.push_back(&newFriend);
48 * // If the db insertion that follows fails, we should
49 * // remove it from memory.
50 * // (You could also declare this as "auto guard = makeGuard(...)")
51 * ScopeGuard guard = makeGuard([&] { friends_.pop_back(); });
53 * // this will throw an exception upon error, which
54 * // makes the ScopeGuard execute UserCont::pop_back()
55 * // once the Guard's destructor is called.
56 * db_->addFriend(GetName(), newFriend.GetName());
58 * // an exception was not thrown, so don't execute
63 * Examine ScopeGuardTest.cpp for some more sample usage.
66 * Andrei's and Petru Marginean's CUJ article:
67 * http://drdobbs.com/184403758
68 * and the loki library:
69 * http://loki-lib.sourceforge.net/index.php?n=Idioms.ScopeGuardPointer
70 * and triendl.kj article:
71 * http://www.codeproject.com/KB/cpp/scope_guard.aspx
73 class ScopeGuardImplBase {
75 void dismiss() noexcept {
80 FOLLY_ALWAYS_INLINE static void runAndWarnAboutToCrashOnException(
81 T& function) noexcept {
91 ScopeGuardImplBase() noexcept : dismissed_(false) {}
93 static ScopeGuardImplBase makeEmptyScopeGuard() noexcept {
94 return ScopeGuardImplBase{};
98 static const T& asConst(const T& t) noexcept {
105 static void warnAboutToCrash() noexcept;
108 template <typename FunctionType>
109 class ScopeGuardImpl : public ScopeGuardImplBase {
111 explicit ScopeGuardImpl(FunctionType& fn) noexcept(
112 std::is_nothrow_copy_constructible<FunctionType>::value)
115 makeFailsafe(std::is_nothrow_copy_constructible<FunctionType>{},
118 explicit ScopeGuardImpl(const FunctionType& fn) noexcept(
119 std::is_nothrow_copy_constructible<FunctionType>::value)
122 makeFailsafe(std::is_nothrow_copy_constructible<FunctionType>{},
125 explicit ScopeGuardImpl(FunctionType&& fn) noexcept(
126 std::is_nothrow_move_constructible<FunctionType>::value)
128 std::move_if_noexcept(fn),
129 makeFailsafe(std::is_nothrow_move_constructible<FunctionType>{},
132 ScopeGuardImpl(ScopeGuardImpl&& other) noexcept(
133 std::is_nothrow_move_constructible<FunctionType>::value)
134 : function_(std::move_if_noexcept(other.function_)) {
135 // If the above line attempts a copy and the copy throws, other is
136 // left owning the cleanup action and will execute it (or not) depending
137 // on the value of other.dismissed_. The following lines only execute
138 // if the move/copy succeeded, in which case *this assumes ownership of
139 // the cleanup action and dismisses other.
140 dismissed_ = other.dismissed_;
141 other.dismissed_ = true;
144 ~ScopeGuardImpl() noexcept {
151 static ScopeGuardImplBase makeFailsafe(std::true_type, const void*) noexcept {
152 return makeEmptyScopeGuard();
155 template <typename Fn>
156 static auto makeFailsafe(std::false_type, Fn* fn) noexcept
157 -> ScopeGuardImpl<decltype(std::ref(*fn))> {
158 return ScopeGuardImpl<decltype(std::ref(*fn))>{std::ref(*fn)};
161 template <typename Fn>
162 explicit ScopeGuardImpl(Fn&& fn, ScopeGuardImplBase&& failsafe)
163 : ScopeGuardImplBase{}, function_(std::forward<Fn>(fn)) {
167 void* operator new(std::size_t) = delete;
169 void execute() noexcept {
170 runAndWarnAboutToCrashOnException(function_);
173 FunctionType function_;
176 template <typename FunctionType>
177 ScopeGuardImpl<typename std::decay<FunctionType>::type>
178 makeGuard(FunctionType&& fn) noexcept(
179 std::is_nothrow_constructible<typename std::decay<FunctionType>::type,
180 FunctionType>::value) {
181 return ScopeGuardImpl<typename std::decay<FunctionType>::type>(
182 std::forward<FunctionType>(fn));
186 * This is largely unneeded if you just use auto for your guards.
188 typedef ScopeGuardImplBase&& ScopeGuard;
192 #if defined(FOLLY_EXCEPTION_COUNT_USE_CXA_GET_GLOBALS) || \
193 defined(FOLLY_EXCEPTION_COUNT_USE_GETPTD) || \
194 defined(FOLLY_EXCEPTION_COUNT_USE_STD)
197 * ScopeGuard used for executing a function when leaving the current scope
198 * depending on the presence of a new uncaught exception.
200 * If the executeOnException template parameter is true, the function is
201 * executed if a new uncaught exception is present at the end of the scope.
202 * If the parameter is false, then the function is executed if no new uncaught
203 * exceptions are present at the end of the scope.
205 * Used to implement SCOPE_FAIL and SCOPE_SUCCESS below.
207 template <typename FunctionType, bool executeOnException>
208 class ScopeGuardForNewException {
210 explicit ScopeGuardForNewException(const FunctionType& fn)
214 explicit ScopeGuardForNewException(FunctionType&& fn)
215 : function_(std::move(fn)) {
218 ScopeGuardForNewException(ScopeGuardForNewException&& other)
219 : function_(std::move(other.function_))
220 , exceptionCounter_(std::move(other.exceptionCounter_)) {
223 ~ScopeGuardForNewException() noexcept(executeOnException) {
224 if (executeOnException == exceptionCounter_.isNewUncaughtException()) {
225 if (executeOnException) {
226 ScopeGuardImplBase::runAndWarnAboutToCrashOnException(function_);
234 ScopeGuardForNewException(const ScopeGuardForNewException& other) = delete;
236 void* operator new(std::size_t) = delete;
238 FunctionType function_;
239 UncaughtExceptionCounter exceptionCounter_;
243 * Internal use for the macro SCOPE_FAIL below
245 enum class ScopeGuardOnFail {};
247 template <typename FunctionType>
248 ScopeGuardForNewException<typename std::decay<FunctionType>::type, true>
249 operator+(detail::ScopeGuardOnFail, FunctionType&& fn) {
251 ScopeGuardForNewException<typename std::decay<FunctionType>::type, true>(
252 std::forward<FunctionType>(fn));
256 * Internal use for the macro SCOPE_SUCCESS below
258 enum class ScopeGuardOnSuccess {};
260 template <typename FunctionType>
261 ScopeGuardForNewException<typename std::decay<FunctionType>::type, false>
262 operator+(ScopeGuardOnSuccess, FunctionType&& fn) {
264 ScopeGuardForNewException<typename std::decay<FunctionType>::type, false>(
265 std::forward<FunctionType>(fn));
268 #endif // native uncaught_exception() supported
271 * Internal use for the macro SCOPE_EXIT below
273 enum class ScopeGuardOnExit {};
275 template <typename FunctionType>
276 ScopeGuardImpl<typename std::decay<FunctionType>::type>
277 operator+(detail::ScopeGuardOnExit, FunctionType&& fn) {
278 return ScopeGuardImpl<typename std::decay<FunctionType>::type>(
279 std::forward<FunctionType>(fn));
281 } // namespace detail
286 auto FB_ANONYMOUS_VARIABLE(SCOPE_EXIT_STATE) \
287 = ::folly::detail::ScopeGuardOnExit() + [&]() noexcept
289 #if defined(FOLLY_EXCEPTION_COUNT_USE_CXA_GET_GLOBALS) || \
290 defined(FOLLY_EXCEPTION_COUNT_USE_GETPTD) || \
291 defined(FOLLY_EXCEPTION_COUNT_USE_STD)
293 auto FB_ANONYMOUS_VARIABLE(SCOPE_FAIL_STATE) \
294 = ::folly::detail::ScopeGuardOnFail() + [&]() noexcept
296 #define SCOPE_SUCCESS \
297 auto FB_ANONYMOUS_VARIABLE(SCOPE_SUCCESS_STATE) \
298 = ::folly::detail::ScopeGuardOnSuccess() + [&]()
299 #endif // native uncaught_exception() supported