2 * Copyright 2013 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.
17 #ifndef FOLLY_SCOPEGUARD_H_
18 #define FOLLY_SCOPEGUARD_H_
24 #include "folly/Preprocessor.h"
25 #include "folly/detail/UncaughtExceptionCounter.h"
30 * ScopeGuard is a general implementation of the "Initialization is
31 * Resource Acquisition" idiom. Basically, it guarantees that a function
32 * is executed upon leaving the currrent scope unless otherwise told.
34 * The makeGuard() function is used to create a new ScopeGuard object.
35 * It can be instantiated with a lambda function, a std::function<void()>,
36 * a functor, or a void(*)() function pointer.
39 * Usage example: Add a friend to memory iff it is also added to the db.
41 * void User::addFriend(User& newFriend) {
42 * // add the friend to memory
43 * friends_.push_back(&newFriend);
45 * // If the db insertion that follows fails, we should
46 * // remove it from memory.
47 * // (You could also declare this as "auto guard = makeGuard(...)")
48 * ScopeGuard guard = makeGuard([&] { friends_.pop_back(); });
50 * // this will throw an exception upon error, which
51 * // makes the ScopeGuard execute UserCont::pop_back()
52 * // once the Guard's destructor is called.
53 * db_->addFriend(GetName(), newFriend.GetName());
55 * // an exception was not thrown, so don't execute
60 * Examine ScopeGuardTest.cpp for some more sample usage.
63 * Andrei's and Petru Marginean's CUJ article:
64 * http://drdobbs.com/184403758
65 * and the loki library:
66 * http://loki-lib.sourceforge.net/index.php?n=Idioms.ScopeGuardPointer
67 * and triendl.kj article:
68 * http://www.codeproject.com/KB/cpp/scope_guard.aspx
70 class ScopeGuardImplBase {
72 void dismiss() noexcept {
78 : dismissed_(false) {}
80 ScopeGuardImplBase(ScopeGuardImplBase&& other)
81 : dismissed_(other.dismissed_) {
82 other.dismissed_ = true;
88 template <typename FunctionType>
89 class ScopeGuardImpl : public ScopeGuardImplBase {
91 explicit ScopeGuardImpl(const FunctionType& fn)
94 explicit ScopeGuardImpl(FunctionType&& fn)
95 : function_(std::move(fn)) {}
97 ScopeGuardImpl(ScopeGuardImpl&& other)
98 : ScopeGuardImplBase(std::move(other))
99 , function_(std::move(other.function_)) {
102 ~ScopeGuardImpl() noexcept {
109 void* operator new(size_t) = delete;
111 void execute() noexcept { function_(); }
113 FunctionType function_;
116 template <typename FunctionType>
117 ScopeGuardImpl<typename std::decay<FunctionType>::type>
118 makeGuard(FunctionType&& fn) {
119 return ScopeGuardImpl<typename std::decay<FunctionType>::type>(
120 std::forward<FunctionType>(fn));
124 * This is largely unneeded if you just use auto for your guards.
126 typedef ScopeGuardImplBase&& ScopeGuard;
130 #if defined(FOLLY_EXCEPTION_COUNT_USE_CXA_GET_GLOBALS) || \
131 defined(FOLLY_EXCEPTION_COUNT_USE_GETPTD)
134 * ScopeGuard used for executing a function when leaving the current scope
135 * depending on the presence of a new uncaught exception.
137 * If the executeOnException template parameter is true, the function is
138 * executed if a new uncaught exception is present at the end of the scope.
139 * If the parameter is false, then the function is executed if no new uncaught
140 * exceptions are present at the end of the scope.
142 * Used to implement SCOPE_FAIL and SCOPE_SUCCES below.
144 template <typename FunctionType, bool executeOnException>
145 class ScopeGuardForNewException {
147 explicit ScopeGuardForNewException(const FunctionType& fn)
151 explicit ScopeGuardForNewException(FunctionType&& fn)
152 : function_(std::move(fn)) {
155 ScopeGuardForNewException(ScopeGuardForNewException&& other)
156 : function_(std::move(other.function_))
157 , exceptionCounter_(std::move(other.exceptionCounter_)) {
160 ~ScopeGuardForNewException() noexcept {
161 if (executeOnException == exceptionCounter_.isNewUncaughtException()) {
167 ScopeGuardForNewException(const ScopeGuardForNewException& other) = delete;
169 void* operator new(size_t) = delete;
171 void execute() noexcept { function_(); }
173 FunctionType function_;
174 UncaughtExceptionCounter exceptionCounter_;
178 * Internal use for the macro SCOPE_FAIL below
180 enum class ScopeGuardOnFail {};
182 template <typename FunctionType>
183 ScopeGuardForNewException<typename std::decay<FunctionType>::type, true>
184 operator+(detail::ScopeGuardOnFail, FunctionType&& fn) {
186 ScopeGuardForNewException<typename std::decay<FunctionType>::type, true>(
187 std::forward<FunctionType>(fn));
191 * Internal use for the macro SCOPE_SUCCESS below
193 enum class ScopeGuardOnSuccess {};
195 template <typename FunctionType>
196 ScopeGuardForNewException<typename std::decay<FunctionType>::type, false>
197 operator+(ScopeGuardOnSuccess, FunctionType&& fn) {
199 ScopeGuardForNewException<typename std::decay<FunctionType>::type, false>(
200 std::forward<FunctionType>(fn));
203 #endif // native uncaught_exception() supported
206 * Internal use for the macro SCOPE_EXIT below
208 enum class ScopeGuardOnExit {};
210 template <typename FunctionType>
211 ScopeGuardImpl<typename std::decay<FunctionType>::type>
212 operator+(detail::ScopeGuardOnExit, FunctionType&& fn) {
213 return ScopeGuardImpl<typename std::decay<FunctionType>::type>(
214 std::forward<FunctionType>(fn));
216 } // namespace detail
221 auto FB_ANONYMOUS_VARIABLE(SCOPE_EXIT_STATE) \
222 = ::folly::detail::ScopeGuardOnExit() + [&]
224 #if defined(FOLLY_EXCEPTION_COUNT_USE_CXA_GET_GLOBALS) || \
225 defined(FOLLY_EXCEPTION_COUNT_USE_GETPTD)
227 auto FB_ANONYMOUS_VARIABLE(SCOPE_FAIL_STATE) \
228 = ::folly::detail::ScopeGuardOnFail() + [&]
230 #define SCOPE_SUCCESS \
231 auto FB_ANONYMOUS_VARIABLE(SCOPE_SUCCESS_STATE) \
232 = ::folly::detail::ScopeGuardOnSuccess() + [&]
233 #endif // native uncaught_exception() supported
235 #endif // FOLLY_SCOPEGUARD_H_