summaryrefslogtreecommitdiff
path: root/libadhocutil/handle.h
blob: 73631834fee9794b8bb33af54599172648f13c30 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#ifndef ADHOCUTIL_HANDLE_H
#define ADHOCUTIL_HANDLE_H

#include <utility>
#include "c++11Helpers.h"

namespace AdHoc {
	/// A unique_ptr like construct for non-pointer objects.
	/// Implements RAII.
	template<typename T, typename D>
	class Handle {
		public:
			/// Constructs a Handle that owns t, to be tidied with d
			Handle(T t, D d) noexcept :
				inst(std::move(t)),
				deleter(std::move(d)),
				owning(true)
			{
			}

			/// Constructs a Handle that takes over ownership of h
			Handle(Handle && h) noexcept :
				inst(std::move(h.inst)),
				deleter(std::move(h.deleter)),
				owning(h.owning)
			{
				h.owning = false;
			}

			~Handle()
			{
				if (owning) {
					deleter(inst);
				}
			}

			/// Standard special members
			SPECIAL_MEMBERS_COPY(Handle, delete);

			/// Takes over ownership of h
			Handle & operator=(Handle && h) noexcept
			{
				if (owning) {
					deleter(inst);
				}
				inst = std::move(h.inst);
				deleter = std::move(h.deleter);
				owning = h.owning;
				h.owning = false;
			}

			/// Returns a reference to the managed object.
			[[nodiscard]] T & get() noexcept { return inst; }
			/// Returns a const reference to the managed object.
			[[nodiscard]] const T & get() const noexcept { return inst; }

			/// Returns a pointer to the managed object.
			[[nodiscard]] T * operator->() noexcept { return inst; }
			/// Returns a const pointer to the managed object.
			[[nodiscard]] const T * operator->() const noexcept { return inst; }

			/// Returns a reference to the managed object.
			[[nodiscard]] T & operator*() noexcept { return inst; }
			/// Returns a const reference to the managed object.
			[[nodiscard]] const T & operator*() const noexcept { return inst; }

			/// Returns a reference to the managed object.
			// NOLINTNEXTLINE(hicpp-explicit-conversions)
			operator T &() noexcept { return inst; }
			/// Returns a const reference to the managed object.
			// NOLINTNEXTLINE(hicpp-explicit-conversions)
			operator const T &() const noexcept { return inst; }

		private:
			T inst;
			D deleter;
			bool owning;
	};

	template<typename T, typename D, typename... Args>
	Handle<T, D> make_handle(D && d, Args && ... args)
	{
		return { T(std::forward<Args>(args)...), std::forward<D>(d) };
	}
}

#endif