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