2 * Copyright 2014 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(executeOnException) {
161 if (executeOnException == exceptionCounter_.isNewUncaughtException()) {
167 ScopeGuardForNewException(const ScopeGuardForNewException& other) = delete;
169 void* operator new(size_t) = delete;
171 FunctionType function_;
172 UncaughtExceptionCounter exceptionCounter_;
176 * Internal use for the macro SCOPE_FAIL below
178 enum class ScopeGuardOnFail {};
180 template <typename FunctionType>
181 ScopeGuardForNewException<typename std::decay<FunctionType>::type, true>
182 operator+(detail::ScopeGuardOnFail, FunctionType&& fn) {
184 ScopeGuardForNewException<typename std::decay<FunctionType>::type, true>(
185 std::forward<FunctionType>(fn));
189 * Internal use for the macro SCOPE_SUCCESS below
191 enum class ScopeGuardOnSuccess {};
193 template <typename FunctionType>
194 ScopeGuardForNewException<typename std::decay<FunctionType>::type, false>
195 operator+(ScopeGuardOnSuccess, FunctionType&& fn) {
197 ScopeGuardForNewException<typename std::decay<FunctionType>::type, false>(
198 std::forward<FunctionType>(fn));
201 #endif // native uncaught_exception() supported
204 * Internal use for the macro SCOPE_EXIT below
206 enum class ScopeGuardOnExit {};
208 template <typename FunctionType>
209 ScopeGuardImpl<typename std::decay<FunctionType>::type>
210 operator+(detail::ScopeGuardOnExit, FunctionType&& fn) {
211 return ScopeGuardImpl<typename std::decay<FunctionType>::type>(
212 std::forward<FunctionType>(fn));
214 } // namespace detail
219 auto FB_ANONYMOUS_VARIABLE(SCOPE_EXIT_STATE) \
220 = ::folly::detail::ScopeGuardOnExit() + [&]() noexcept
222 #if defined(FOLLY_EXCEPTION_COUNT_USE_CXA_GET_GLOBALS) || \
223 defined(FOLLY_EXCEPTION_COUNT_USE_GETPTD)
225 auto FB_ANONYMOUS_VARIABLE(SCOPE_FAIL_STATE) \
226 = ::folly::detail::ScopeGuardOnFail() + [&]() noexcept
228 #define SCOPE_SUCCESS \
229 auto FB_ANONYMOUS_VARIABLE(SCOPE_SUCCESS_STATE) \
230 = ::folly::detail::ScopeGuardOnSuccess() + [&]()
231 #endif // native uncaught_exception() supported
233 #endif // FOLLY_SCOPEGUARD_H_