• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2014 The Android Open Source Project
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 ANDROID_BASE_SCOPEGUARD_H
18 #define ANDROID_BASE_SCOPEGUARD_H
19 
20 #include <utility>  // for std::move, std::forward
21 
22 namespace android {
23 namespace base {
24 
25 // ScopeGuard ensures that the specified functor is executed no matter how the
26 // current scope exits.
27 template <typename F>
28 class ScopeGuard {
29  public:
ScopeGuard(F && f)30   ScopeGuard(F&& f) : f_(std::forward<F>(f)), active_(true) {}
31 
ScopeGuard(ScopeGuard && that)32   ScopeGuard(ScopeGuard&& that) : f_(std::move(that.f_)), active_(that.active_) {
33     that.active_ = false;
34   }
35 
36   template <typename Functor>
ScopeGuard(ScopeGuard<Functor> && that)37   ScopeGuard(ScopeGuard<Functor>&& that) : f_(std::move(that.f_)), active_(that.active_) {
38     that.active_ = false;
39   }
40 
~ScopeGuard()41   ~ScopeGuard() {
42     if (active_) f_();
43   }
44 
45   ScopeGuard() = delete;
46   ScopeGuard(const ScopeGuard&) = delete;
47   void operator=(const ScopeGuard&) = delete;
48   void operator=(ScopeGuard&& that) = delete;
49 
Disable()50   void Disable() { active_ = false; }
51 
active()52   bool active() const { return active_; }
53 
54  private:
55   template <typename Functor>
56   friend class ScopeGuard;
57 
58   F f_;
59   bool active_;
60 };
61 
62 template <typename F>
make_scope_guard(F && f)63 ScopeGuard<F> make_scope_guard(F&& f) {
64   return ScopeGuard<F>(std::forward<F>(f));
65 }
66 
67 }  // namespace base
68 }  // namespace android
69 
70 #endif  // ANDROID_BASE_SCOPEGUARD_H
71