open62541pp 0.15.0
C++ wrapper of open62541
Loading...
Searching...
No Matches
scope.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <functional> // invoke
4#include <type_traits>
5#include <utility> // move
6
7namespace opcua::detail {
8
9/**
10 * General-purpose scope guard intended to call its exit function when a scope is exited.
11 * @see https://en.cppreference.com/w/cpp/experimental/scope_exit
12 */
13template <typename Fn>
14class [[nodiscard]] ScopeExit {
15public:
16 static_assert(std::is_nothrow_move_constructible_v<Fn>);
17 static_assert(std::is_invocable_v<Fn>);
18
19 explicit ScopeExit(Fn&& fn) noexcept
20 : fn_(std::move(fn)) {}
21
22 ScopeExit(ScopeExit&& other) noexcept
23 : fn_(std::move(other.fn_)),
24 active_(other.active_) {
25 other.release();
26 }
27
28 ~ScopeExit() noexcept(std::is_nothrow_invocable_v<Fn>) {
29 if (active_) {
30 std::invoke(fn_);
31 }
32 }
33
34 ScopeExit(const ScopeExit&) = delete;
35 ScopeExit& operator=(const ScopeExit&) = delete;
37
38 void release() noexcept {
39 active_ = false;
40 }
41
42private:
43 Fn fn_;
44 bool active_{true};
45};
46
47} // namespace opcua::detail
General-purpose scope guard intended to call its exit function when a scope is exited.
Definition scope.hpp:14
ScopeExit(ScopeExit &&other) noexcept
Definition scope.hpp:22
ScopeExit(Fn &&fn) noexcept
Definition scope.hpp:19
ScopeExit(const ScopeExit &)=delete
~ScopeExit() noexcept(std::is_nothrow_invocable_v< Fn >)
Definition scope.hpp:28
void release() noexcept
Definition scope.hpp:38
ScopeExit & operator=(const ScopeExit &)=delete
ScopeExit & operator=(ScopeExit &&)=delete