2 * Copyright 2011-present 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/UncaughtExceptions.h>
33 class ScopeGuardImplBase {
35 void dismiss() noexcept {
40 FOLLY_ALWAYS_INLINE static void runAndWarnAboutToCrashOnException(
41 T& function) noexcept {
51 ScopeGuardImplBase() noexcept : dismissed_(false) {}
53 static ScopeGuardImplBase makeEmptyScopeGuard() noexcept {
54 return ScopeGuardImplBase{};
58 static const T& asConst(const T& t) noexcept {
65 static void warnAboutToCrash() noexcept;
68 template <typename FunctionType>
69 class ScopeGuardImpl : public ScopeGuardImplBase {
71 explicit ScopeGuardImpl(FunctionType& fn) noexcept(
72 std::is_nothrow_copy_constructible<FunctionType>::value)
75 makeFailsafe(std::is_nothrow_copy_constructible<FunctionType>{},
78 explicit ScopeGuardImpl(const FunctionType& fn) noexcept(
79 std::is_nothrow_copy_constructible<FunctionType>::value)
82 makeFailsafe(std::is_nothrow_copy_constructible<FunctionType>{},
85 explicit ScopeGuardImpl(FunctionType&& fn) noexcept(
86 std::is_nothrow_move_constructible<FunctionType>::value)
88 std::move_if_noexcept(fn),
89 makeFailsafe(std::is_nothrow_move_constructible<FunctionType>{},
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;
104 ~ScopeGuardImpl() noexcept {
111 static ScopeGuardImplBase makeFailsafe(std::true_type, const void*) noexcept {
112 return makeEmptyScopeGuard();
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)};
121 template <typename Fn>
122 explicit ScopeGuardImpl(Fn&& fn, ScopeGuardImplBase&& failsafe)
123 : ScopeGuardImplBase{}, function_(std::forward<Fn>(fn)) {
127 void* operator new(std::size_t) = delete;
129 void execute() noexcept {
130 runAndWarnAboutToCrashOnException(function_);
133 FunctionType function_;
136 template <typename F>
137 using ScopeGuardImplDecay = ScopeGuardImpl<typename std::decay<F>::type>;
139 } // namespace detail
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.
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.
151 * Usage example: Add a friend to memory if and only if it is also added
154 * void User::addFriend(User& newFriend) {
155 * // add the friend to memory
156 * friends_.push_back(&newFriend);
158 * // If the db insertion that follows fails, we should
159 * // remove it from memory.
160 * auto guard = makeGuard([&] { friends_.pop_back(); });
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());
167 * // an exception was not thrown, so don't execute
172 * Examine ScopeGuardTest.cpp for some more sample usage.
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
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));
190 #if defined(FOLLY_EXCEPTION_COUNT_USE_CXA_GET_GLOBALS) || \
191 defined(FOLLY_EXCEPTION_COUNT_USE_GETPTD) || \
192 defined(FOLLY_EXCEPTION_COUNT_USE_STD)
195 * ScopeGuard used for executing a function when leaving the current scope
196 * depending on the presence of a new uncaught exception.
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.
203 * Used to implement SCOPE_FAIL and SCOPE_SUCCESS below.
205 template <typename FunctionType, bool ExecuteOnException>
206 class ScopeGuardForNewException {
208 explicit ScopeGuardForNewException(const FunctionType& fn) : function_(fn) {}
210 explicit ScopeGuardForNewException(FunctionType&& fn)
211 : function_(std::move(fn)) {}
213 ScopeGuardForNewException(ScopeGuardForNewException&& other) = default;
215 ~ScopeGuardForNewException() noexcept(ExecuteOnException) {
216 if (ExecuteOnException == (exceptionCounter_ < uncaught_exceptions())) {
217 if (ExecuteOnException) {
218 ScopeGuardImplBase::runAndWarnAboutToCrashOnException(function_);
226 ScopeGuardForNewException(const ScopeGuardForNewException& other) = delete;
228 void* operator new(std::size_t) = delete;
230 FunctionType function_;
231 int exceptionCounter_{uncaught_exceptions()};
235 * Internal use for the macro SCOPE_FAIL below
237 enum class ScopeGuardOnFail {};
239 template <typename FunctionType>
240 ScopeGuardForNewException<typename std::decay<FunctionType>::type, true>
241 operator+(detail::ScopeGuardOnFail, FunctionType&& fn) {
243 ScopeGuardForNewException<typename std::decay<FunctionType>::type, true>(
244 std::forward<FunctionType>(fn));
248 * Internal use for the macro SCOPE_SUCCESS below
250 enum class ScopeGuardOnSuccess {};
252 template <typename FunctionType>
253 ScopeGuardForNewException<typename std::decay<FunctionType>::type, false>
254 operator+(ScopeGuardOnSuccess, FunctionType&& fn) {
256 ScopeGuardForNewException<typename std::decay<FunctionType>::type, false>(
257 std::forward<FunctionType>(fn));
260 #endif // native uncaught_exception() supported
263 * Internal use for the macro SCOPE_EXIT below
265 enum class ScopeGuardOnExit {};
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));
273 } // namespace detail
278 auto FB_ANONYMOUS_VARIABLE(SCOPE_EXIT_STATE) \
279 = ::folly::detail::ScopeGuardOnExit() + [&]() noexcept
281 #if defined(FOLLY_EXCEPTION_COUNT_USE_CXA_GET_GLOBALS) || \
282 defined(FOLLY_EXCEPTION_COUNT_USE_GETPTD) || \
283 defined(FOLLY_EXCEPTION_COUNT_USE_STD)
285 auto FB_ANONYMOUS_VARIABLE(SCOPE_FAIL_STATE) \
286 = ::folly::detail::ScopeGuardOnFail() + [&]() noexcept
288 #define SCOPE_SUCCESS \
289 auto FB_ANONYMOUS_VARIABLE(SCOPE_SUCCESS_STATE) \
290 = ::folly::detail::ScopeGuardOnSuccess() + [&]()
291 #endif // native uncaught_exception() supported