Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100644 158 lines (135 sloc) 4.355 kB
27494a2 @jdelong Pull from FB rev 63ce89e2f2301e6bba44a111cc7d4218022156f6
jdelong authored
1 /*
2 * Copyright 2012 Facebook, Inc.
3 *
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
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
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.
15 */
16
17 #ifndef FOLLY_SCOPEGUARD_H_
18 #define FOLLY_SCOPEGUARD_H_
19
20 #include <cstddef>
21 #include <functional>
22 #include <new>
23 #include <glog/logging.h>
24
25 #include "folly/Preprocessor.h"
26
27 namespace folly {
28
29 /**
30 * ScopeGuard is a general implementation of the "Initilization is
31 * Resource Acquisition" idiom. Basically, it guarantees that a function
32 * is executed upon leaving the currrent scope unless otherwise told.
33 *
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.
37 *
38 *
39 * Usage example: Add a friend to memory iff it is also added to the db.
40 *
41 * void User::addFriend(User& newFriend) {
42 * // add the friend to memory
43 * friends_.push_back(&newFriend);
44 *
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(); });
49 *
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());
54 *
55 * // an exception was not thrown, so don't execute
56 * // the Guard.
57 * guard.dismiss();
58 * }
59 *
60 * Examine ScopeGuardTest.cpp for some more sample usage.
61 *
62 * Stolen from:
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
69 */
70 class ScopeGuardImplBase {
71 public:
72 void dismiss() noexcept {
73 dismissed_ = true;
74 }
75
76 protected:
77 ScopeGuardImplBase()
78 : dismissed_(false) {}
79
80 ScopeGuardImplBase(ScopeGuardImplBase&& other)
81 : dismissed_(other.dismissed_) {
82 other.dismissed_ = true;
83 }
84
85 bool dismissed_;
86 };
87
88 template<typename FunctionType>
89 class ScopeGuardImpl : public ScopeGuardImplBase {
90 public:
91 explicit ScopeGuardImpl(const FunctionType& fn)
92 : function_(fn) {}
93
94 explicit ScopeGuardImpl(FunctionType&& fn)
95 : function_(std::move(fn)) {}
96
97 ScopeGuardImpl(ScopeGuardImpl&& other)
98 : ScopeGuardImplBase(std::move(other)),
99 function_(std::move(other.function_)) {
100 }
101
102 ~ScopeGuardImpl() noexcept {
103 if (!dismissed_) {
104 execute();
105 }
106 }
107
108 private:
109 void* operator new(size_t) = delete;
110
111 void execute() noexcept {
112 try {
113 function_();
114 } catch (const std::exception& ex) {
115 LOG(FATAL) << "ScopeGuard cleanup function threw a " <<
116 typeid(ex).name() << "exception: " << ex.what();
117 } catch (...) {
118 LOG(FATAL) << "ScopeGuard cleanup function threw a non-exception object";
119 }
120 }
121
122 FunctionType function_;
123 };
124
125 template<typename FunctionType>
126 ScopeGuardImpl<typename std::decay<FunctionType>::type>
127 makeGuard(FunctionType&& fn) {
128 return ScopeGuardImpl<typename std::decay<FunctionType>::type>(
129 std::forward<FunctionType>(fn));
130 }
131
132 /**
133 * This is largely unneeded if you just use auto for your guards.
134 */
135 typedef ScopeGuardImplBase&& ScopeGuard;
136
137 namespace detail {
138 /**
139 * Internal use for the macro SCOPE_EXIT below
140 */
141 enum class ScopeGuardOnExit {};
142
143 template <typename FunctionType>
144 ScopeGuardImpl<typename std::decay<FunctionType>::type>
145 operator+(detail::ScopeGuardOnExit, FunctionType&& fn) {
146 return ScopeGuardImpl<typename std::decay<FunctionType>::type>(
147 std::forward<FunctionType>(fn));
148 }
149 } // namespace detail
150
151 } // folly
152
153 #define SCOPE_EXIT \
154 auto FB_ANONYMOUS_VARIABLE(SCOPE_EXIT_STATE) \
155 = ::folly::detail::ScopeGuardOnExit() + [&]
156
157 #endif // FOLLY_SCOPEGUARD_H_
Something went wrong with that request. Please try again.