• 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
21 
22 namespace android {
23 namespace base {
24 
25 template <typename F>
26 class ScopeGuard {
27  public:
ScopeGuard(F f)28   ScopeGuard(F f) : f_(f), active_(true) {}
29 
ScopeGuard(ScopeGuard && that)30   ScopeGuard(ScopeGuard&& that) : f_(std::move(that.f_)), active_(that.active_) {
31     that.active_ = false;
32   }
33 
~ScopeGuard()34   ~ScopeGuard() {
35     if (active_) f_();
36   }
37 
38   ScopeGuard() = delete;
39   ScopeGuard(const ScopeGuard&) = delete;
40   void operator=(const ScopeGuard&) = delete;
41   void operator=(ScopeGuard&& that) = delete;
42 
Disable()43   void Disable() { active_ = false; }
44 
active()45   bool active() const { return active_; }
46 
47  private:
48   F f_;
49   bool active_;
50 };
51 
52 template <typename T>
make_scope_guard(T f)53 ScopeGuard<T> make_scope_guard(T f) {
54   return ScopeGuard<T>(f);
55 }
56 
57 }  // namespace base
58 }  // namespace android
59 
60 #endif  // ANDROID_BASE_SCOPEGUARD_H
61