• 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 SCOPE_GUARD_H
18 #define SCOPE_GUARD_H
19 
20 // TODO: include explicit std::move when it becomes available
21 template<typename F>
22 class ScopeGuard {
23  public:
ScopeGuard(F f)24   ScopeGuard(F f) : f_(f), active_(true) {}
25 
ScopeGuard(ScopeGuard && that)26   ScopeGuard(ScopeGuard&& that) : f_(that.f_), active_(that.active_) {
27     that.active_ = false;
28   }
29 
~ScopeGuard()30   ~ScopeGuard() {
31     if (active_) {
32       f_();
33     }
34   }
35 
disable()36   void disable() {
37     active_ = false;
38   }
39  private:
40   F f_;
41   bool active_;
42 
43   ScopeGuard() = delete;
44   ScopeGuard(const ScopeGuard&) = delete;
45   ScopeGuard& operator=(const ScopeGuard&) = delete;
46 };
47 
48 template<typename T>
create_scope_guard(T f)49 ScopeGuard<T> create_scope_guard(T f) {
50   return ScopeGuard<T>(f);
51 }
52 
53 #endif  // SCOPE_GUARD_H
54