tetl 0.1.0
Embedded Template Library
Loading...
Searching...
No Matches
scope_guard.hpp
Go to the documentation of this file.
1// SPDX-License-Identifier: BSL-1.0
2// SPDX-FileCopyrightText: Copyright (C) 2020 Tobias Hienzsch
3#ifndef TETL_SCOPE_SCOPE_GUARD_HPP
4#define TETL_SCOPE_SCOPE_GUARD_HPP
5
6#include <etl/_type_traits/decay.hpp>
7#include <etl/_utility/forward.hpp>
8#include <etl/_utility/move.hpp>
9
10namespace etl::detail {
11template <typename FuncT, typename PolicyT>
12struct scope_guard {
13public:
14 template <typename F>
15 explicit constexpr scope_guard(F&& f)
16 : _func{etl::forward<F>(f)}
17 {
18 }
19
20 constexpr scope_guard(scope_guard&& rhs) noexcept
21 : _func{etl::move(rhs._func)}
22 , _policy{etl::move(rhs._policy)}
23 {
24 }
25
26 constexpr ~scope_guard()
27 {
28 if (_policy) {
29 _func();
30 }
31 }
32
33 constexpr auto release() noexcept -> void
34 {
35 _policy.release();
36 }
37
38 scope_guard(scope_guard const&) = delete;
39 auto operator=(scope_guard const&) -> scope_guard& = delete;
40 auto operator=(scope_guard&&) -> scope_guard& = delete;
41
42private:
43 FuncT _func;
44 PolicyT _policy{};
45};
46
47struct scope_exit_impl {
48 constexpr scope_exit_impl() = default;
49
50 constexpr scope_exit_impl(scope_exit_impl&& rhs) noexcept
51 : should_execute{rhs.should_execute}
52 {
53 rhs.release();
54 }
55
56 constexpr auto release() noexcept -> void
57 {
58 should_execute = false;
59 }
60
61 explicit constexpr operator bool() const noexcept
62 {
63 return should_execute;
64 }
65
66 bool should_execute = true;
67};
68} // namespace etl::detail
69
70#endif // TETL_SCOPE_SCOPE_GUARD_HPP
Definition adjacent_find.hpp:9