1 /* 2 * htwg_unique_ptr.h 3 * 4 * Stark vereinfachter unique_ptr. 5 * 6 * Autor: H.Drachenfels 7 * Erstellt am: 1.12.2022 8 */
9 #ifndef HTWG_UNIQUE_PTR_H
10 #define HTWG_UNIQUE_PTR_H
11
12 namespace htwg
13 {
14 template<typename T>
15 class unique_ptr final
16 {
17 private:
18 T *p;
19 public:
20 unique_ptr()
21 : p(nullptr)
22 { }
23
24 explicit unique_ptr(T *q)
25 : p(q)
26 { }
27
28 ~unique_ptr()
29 {
30 delete this->p;
31 }
32
33 unique_ptr(const unique_ptr& v) = delete;
34 unique_ptr& operator=(const unique_ptr& v) = delete;
35
36 unique_ptr(unique_ptr&& v)
37 : p(v.p)
38 {
39 v.p = nullptr;
40 }
41
42 unique_ptr& operator=(unique_ptr&& v)
43 {
44 if (this != &v)
45 {
46 delete this->p;
47 this->p = v.p;
48 v.p = nullptr;
49 }
50 return *this;
51 }
52
53 T* get() const
54 {
55 return this->p;
56 }
57
58 operator bool() const
59 {
60 return this->p != nullptr;
61 }
62
63 T& operator*() const
64 {
65 return *this->p;
66 }
67
68 T* operator->() const
69 {
70 return this->p;
71 }
72 };
73
74 template<typename T>
75 bool operator==(const unique_ptr<T>& u, const unique_ptr<T>& v)
76 {
77 return u.get() == v.get();
78 }
79
80 template<typename T>
81 bool operator!=(const unique_ptr<T>& u, const unique_ptr<T>& v)
82 {
83 return u.get() != v.get();
84 }
85 }
86
87 #endif
88