summaryrefslogtreecommitdiff
path: root/lib/ptr.hpp
blob: 931df39388caa223309f9fc1c46765700a81b48e (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
#pragma once

#include <memory>
#include <special_members.hpp>

template<typename Obj, auto Destroy> class wrapped_ptr {
public:
	template<typename... Args, typename... Params>
	explicit wrapped_ptr(Obj * (*factory)(Params...), Args &&... args) : obj {factory(std::forward<Args>(args)...)}
	{
	}

	explicit wrapped_ptr(wrapped_ptr && p) : obj {p.obj}
	{
		p.obj = nullptr;
	}

	~wrapped_ptr()
	{
		if (obj) {
			Destroy(obj);
		}
	}

	NO_COPY(wrapped_ptr);

	wrapped_ptr &
	operator=(wrapped_ptr && p)
	{
		if (obj) {
			Destroy(obj);
		}
		obj = p.obj;
		p.obj = nullptr;
		return *this;
	}

	[[nodiscard]] inline
	operator Obj *() const noexcept
	{
		return obj;
	}

	[[nodiscard]] inline auto
	operator->() const noexcept
	{
		return obj;
	}

	[[nodiscard]] inline auto
	get() const noexcept
	{
		return obj;
	}

protected:
	explicit wrapped_ptr(Obj * o) : obj {o} { }
	Obj * obj;
};

template<typename Obj, auto Create, auto Destroy> class wrapped_ptrt : public wrapped_ptr<Obj, Destroy> {
public:
	template<typename... Args>
	explicit wrapped_ptrt(Args &&... args) : wrapped_ptr<Obj, Destroy> {Create(std::forward<Args>(args)...)}
	{
	}
};