xref: /aosp_15_r20/system/libbase/include/android-base/scopeguard.h (revision 8f0ba417480079999ba552f1087ae592091b9d02)
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   constexpr ScopeGuard(F f) : f_(std::move(f)), active_(true) {}
30 
ScopeGuard(ScopeGuard && that)31   constexpr 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   constexpr ScopeGuard(ScopeGuard<Functor>&& that) noexcept
37       : f_(std::move(that.f_)), active_(that.active_) {
38     that.active_ = false;
39   }
40 
noexcept(noexcept (f_ ()))41   ~ScopeGuard() noexcept(noexcept(f_())) {
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() noexcept { active_ = false; }
51 
active()52   constexpr bool active() const noexcept { 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 auto make_scope_guard(F&& f) {
64   return ScopeGuard<std::remove_reference_t<F>>(std::forward<F>(f));
65 }
66 
67 }  // namespace base
68 }  // namespace android
69