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));
189 * This is largely unneeded if you just use auto for your guards.
191 typedef detail::ScopeGuardImplBase&& ScopeGuard;
195 #if defined(FOLLY_EXCEPTION_COUNT_USE_CXA_GET_GLOBALS) || \
196 defined(FOLLY_EXCEPTION_COUNT_USE_GETPTD) || \
197 defined(FOLLY_EXCEPTION_COUNT_USE_STD)
200 * ScopeGuard used for executing a function when leaving the current scope
201 * depending on the presence of a new uncaught exception.
203 * If the executeOnException template parameter is true, the function is
204 * executed if a new uncaught exception is present at the end of the scope.
205 * If the parameter is false, then the function is executed if no new uncaught
206 * exceptions are present at the end of the scope.
208 * Used to implement SCOPE_FAIL and SCOPE_SUCCESS below.
210 template <typename FunctionType, bool ExecuteOnException>
211 class ScopeGuardForNewException {
213 explicit ScopeGuardForNewException(const FunctionType& fn) : function_(fn) {}
215 explicit ScopeGuardForNewException(FunctionType&& fn)
216 : function_(std::move(fn)) {}
218 ScopeGuardForNewException(ScopeGuardForNewException&& other) = default;
220 ~ScopeGuardForNewException() noexcept(ExecuteOnException) {
221 if (ExecuteOnException == (exceptionCounter_ < uncaught_exceptions())) {
222 if (ExecuteOnException) {
223 ScopeGuardImplBase::runAndWarnAboutToCrashOnException(function_);
231 ScopeGuardForNewException(const ScopeGuardForNewException& other) = delete;
233 void* operator new(std::size_t) = delete;
235 FunctionType function_;
236 int exceptionCounter_{uncaught_exceptions()};
240 * Internal use for the macro SCOPE_FAIL below
242 enum class ScopeGuardOnFail {};
244 template <typename FunctionType>
245 ScopeGuardForNewException<typename std::decay<FunctionType>::type, true>
246 operator+(detail::ScopeGuardOnFail, FunctionType&& fn) {
248 ScopeGuardForNewException<typename std::decay<FunctionType>::type, true>(
249 std::forward<FunctionType>(fn));
253 * Internal use for the macro SCOPE_SUCCESS below
255 enum class ScopeGuardOnSuccess {};
257 template <typename FunctionType>
258 ScopeGuardForNewException<typename std::decay<FunctionType>::type, false>
259 operator+(ScopeGuardOnSuccess, FunctionType&& fn) {
261 ScopeGuardForNewException<typename std::decay<FunctionType>::type, false>(
262 std::forward<FunctionType>(fn));
265 #endif // native uncaught_exception() supported
268 * Internal use for the macro SCOPE_EXIT below
270 enum class ScopeGuardOnExit {};
272 template <typename FunctionType>
273 ScopeGuardImpl<typename std::decay<FunctionType>::type>
274 operator+(detail::ScopeGuardOnExit, FunctionType&& fn) {
275 return ScopeGuardImpl<typename std::decay<FunctionType>::type>(
276 std::forward<FunctionType>(fn));
278 } // namespace detail
283 auto FB_ANONYMOUS_VARIABLE(SCOPE_EXIT_STATE) \
284 = ::folly::detail::ScopeGuardOnExit() + [&]() noexcept
286 #if defined(FOLLY_EXCEPTION_COUNT_USE_CXA_GET_GLOBALS) || \
287 defined(FOLLY_EXCEPTION_COUNT_USE_GETPTD) || \
288 defined(FOLLY_EXCEPTION_COUNT_USE_STD)
290 auto FB_ANONYMOUS_VARIABLE(SCOPE_FAIL_STATE) \
291 = ::folly::detail::ScopeGuardOnFail() + [&]() noexcept
293 #define SCOPE_SUCCESS \
294 auto FB_ANONYMOUS_VARIABLE(SCOPE_SUCCESS_STATE) \
295 = ::folly::detail::ScopeGuardOnSuccess() + [&]()
296 #endif // native uncaught_exception() supported