C/C++ API Reference
Loading...
Searching...
No Matches
scope_guard.h
1// Copyright 2023 The Pigweed Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License"); you may not
4// use this file except in compliance with the License. You may obtain a copy of
5// the License at
6//
7// https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12// License for the specific language governing permissions and limitations under
13// the License.
14#pragma once
15
16#include <utility>
17
18namespace pw {
19
21
39template <typename Functor>
41 public:
42 constexpr ScopeGuard(Functor&& functor)
43 : functor_(std::forward<Functor>(functor)), dismissed_(false) {}
44
45 constexpr ScopeGuard(ScopeGuard&& other) noexcept
46 : functor_(std::move(other.functor_)), dismissed_(other.dismissed_) {
47 other.dismissed_ = true;
48 }
49
50 template <typename OtherFunctor>
51 constexpr ScopeGuard(ScopeGuard<OtherFunctor>&& other)
52 : functor_(std::move(other.functor_)), dismissed_(other.dismissed_) {
53 other.dismissed_ = true;
54 }
55
56 ~ScopeGuard() {
57 if (dismissed_) {
58 return;
59 }
60 functor_();
61 }
62
63 ScopeGuard& operator=(ScopeGuard&& other) noexcept {
64 functor_ = std::move(other.functor_);
65 dismissed_ = std::move(other.dismissed_);
66 other.dismissed_ = true;
67 }
68
69 ScopeGuard() = delete;
70 ScopeGuard(const ScopeGuard&) = delete;
71 ScopeGuard& operator=(const ScopeGuard&) = delete;
72
75 void Dismiss() { dismissed_ = true; }
76
77 private:
78 template <typename OtherFunctor>
79 friend class ScopeGuard;
80
81 Functor functor_;
82 bool dismissed_;
83};
84
85// Enable type deduction for a compatible function pointer.
86template <typename Function>
87ScopeGuard(Function()) -> ScopeGuard<Function (*)()>;
88
89} // namespace pw
Definition: scope_guard.h:40
fit::function_impl< function_internal::config::kInlineCallableSize, !function_internal::config::kEnableDynamicAllocation, FunctionType, PW_FUNCTION_DEFAULT_ALLOCATOR_TYPE > Function
Definition: function.h:73
void Dismiss()
Definition: scope_guard.h:75
The Pigweed namespace.
Definition: alignment.h:27