Android-cuttlefish cvd tool
scopeguard.h
Go to the documentation of this file.
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
21namespace android {
22namespace base {
23
24// ScopeGuard ensures that the specified functor is executed no matter how the
25// current scope exits.
26template <typename F>
28 public:
29 constexpr ScopeGuard(F&& f) : f_(std::forward<F>(f)), active_(true) {}
30
31 constexpr ScopeGuard(ScopeGuard&& that) noexcept : f_(std::move(that.f_)), active_(that.active_) {
32 that.active_ = false;
33 }
34
35 template <typename Functor>
36 constexpr ScopeGuard(ScopeGuard<Functor>&& that) : f_(std::move(that.f_)), active_(that.active_) {
37 that.active_ = false;
38 }
39
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
49 void Disable() { active_ = false; }
50
51 constexpr 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
61template <typename F>
63 return ScopeGuard<F>(std::forward<F>(f));
64}
65
66template<typename F>
68
69} // namespace base
70} // namespace android
Definition: scopeguard.h:27
F f_
Definition: scopeguard.h:57
void Disable()
Definition: scopeguard.h:49
constexpr ScopeGuard(ScopeGuard &&that) noexcept
Definition: scopeguard.h:31
void operator=(ScopeGuard &&that)=delete
void operator=(const ScopeGuard &)=delete
~ScopeGuard()
Definition: scopeguard.h:40
ScopeGuard(const ScopeGuard &)=delete
bool active_
Definition: scopeguard.h:58
constexpr bool active() const
Definition: scopeguard.h:51
constexpr ScopeGuard(ScopeGuard< Functor > &&that)
Definition: scopeguard.h:36
constexpr ScopeGuard(F &&f)
Definition: scopeguard.h:29
ScopeGuard< F > make_scope_guard(F &&f)
Definition: scopeguard.h:62
ScopeGuard(F &&t) -> ScopeGuard< F >
Definition: map_ptr.h:34
Definition: logging.h:464