1 /* 2 * htwg_shared_ptr.h 3 * 4 * Stark vereinfachter shared_ptr. 5 * 6 * Autor: H.Drachenfels 7 * Erstellt am: 7.12.2020 8 */
9 #ifndef HTWG_SHARED_PTR_H
10 #define HTWG_SHARED_PTR_H
11
12 namespace htwg
13 {
14 template<typename T>
15 class shared_ptr final
16 {
17 private:
18 T *p; // verwalteter Zeiger
19 int *n; // Referenzzaehler
20 public:
21 shared_ptr()
22 : p(nullptr), n(nullptr)
23 { }
24
25 explicit shared_ptr(T *q)
26 : p(q), n(new int{1})
27 { }
28
29 ~shared_ptr()
30 {
31 if (this->n && --*this->n == 0)
32 {
33 delete this->p;
34 delete this->n;
35 }
36 }
37
38 shared_ptr(const shared_ptr& v)
39 : p(v.p), n(v.n)
40 {
41 if (this->n)
42 {
43 ++*this->n;
44 }
45 }
46
47 shared_ptr& operator=(const shared_ptr& v)
48 {
49 if (this != &v)
50 {
51 if (this->n && --*this->n == 0)
52 {
53 delete this->p;
54 delete this->n;
55 }
56
57 this->p = v.p;
58 this->n = v.n;
59
60 if (this->n)
61 {
62 ++*this->n;
63 }
64 }
65 return *this;
66 }
67
68 shared_ptr(shared_ptr&& v)
69 : p(v.p), n(v.n)
70 {
71 v.p = nullptr;
72 v.n = nullptr;
73 }
74
75 shared_ptr& operator=(shared_ptr&& v)
76 {
77 if (this != &v)
78 {
79 if (this->n && --*this->n == 0)
80 {
81 delete this->p;
82 delete this->n;
83 }
84
85 this->p = v.p;
86 this->n = v.n;
87 v.p = nullptr;
88 v.n = nullptr;
89 }
90 return *this;
91 }
92
93 T* get() const
94 {
95 return this->p;
96 }
97
98 int use_count() const
99 {
100 return this->n ? *this->n : 0;
101 }
102
103 operator bool()
104 {
105 return this->p != nullptr;
106 }
107
108 T& operator*() const
109 {
110 return *this->p;
111 }
112
113 T* operator->() const
114 {
115 return this->p;
116 }
117 };
118
119 template<typename T>
120 bool operator==(const shared_ptr<T>& u, const shared_ptr<T>& v)
121 {
122 return u.get() == v.get();
123 }
124
125 template<typename T>
126 bool operator!=(const shared_ptr<T>& u, const shared_ptr<T>& v)
127 {
128 return u.get() != v.get();
129 }
130 }
131
132 #endif
133