async_mqtt 4.1.0
Loading...
Searching...
No Matches
scope_guard.hpp
1// Copyright Takatoshi Kondo 2022
2//
3// Distributed under the Boost Software License, Version 1.0.
4// (See accompanying file LICENSE_1_0.txt or copy at
5// http://www.boost.org/LICENSE_1_0.txt)
6
7#if !defined(ASYNC_MQTT_UTIL_UNIQUE_SCOPE_GUARD_HPP)
8#define ASYNC_MQTT_UTIL_UNIQUE_SCOPE_GUARD_HPP
9
10#include <memory>
11#include <utility>
12
13namespace async_mqtt {
14
15namespace detail {
16template <typename Proc>
17class unique_sg {
18public:
19 unique_sg(Proc proc)
20 :proc_{std::move(proc)}
21 {}
22 unique_sg(unique_sg const&) = delete;
23 unique_sg(unique_sg&& other)
24 :proc_{other.proc_} {
25 other.moved_ = true;
26 }
27 ~unique_sg() {
28 if (!moved_) std::move(proc_)();
29 }
30
31private:
32 Proc proc_;
33 bool moved_ = false;
34};
35
36} // namespace detail
37
38template <typename Proc>
39inline detail::unique_sg<Proc> unique_scope_guard(Proc&& proc) {
40 return detail::unique_sg<Proc>{std::forward<Proc>(proc)};
41}
42
43} // namespace async_mqtt
44
45#endif // ASYNC_MQTT_UTIL_UNIQUE_SCOPE_GUARD_HPP