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