-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRCPointer.hpp
87 lines (64 loc) · 1.68 KB
/
RCPointer.hpp
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
#ifndef RCPOINTER_HPP
#define RCPOINTER_HPP
#include <cstddef>
#include "types.h"
template<typename T>
class RCPointer {
private:
T *pointer;
public:
RCPointer(T *pointer = nullptr): pointer(nullptr) {
set(pointer);
}
RCPointer(const RCPointer &other): pointer{nullptr} {
set(other.pointer);
}
RCPointer &operator=(T *other_pointer) {
if(this->pointer != other_pointer) {
set(other_pointer);
}
return *this;
}
bool operator==(const T *other_pointer) const {
return (*pointer == *other_pointer);
}
RCPointer &operator=(const RCPointer &other) {
if(this != &other) {
set(other.pointer);
}
return *this;
}
bool operator==(const RCPointer &other) const {
return (*pointer == *(other.pointer));
}
RCPointer& operator=(std::nullptr_t) {
set(nullptr);
return *this;
}
bool operator==(std::nullptr_t) const {
return (pointer == nullptr);
}
~RCPointer() {
set(nullptr);
}
T &operator*() const { return *pointer; }
T *operator->() const { return pointer; }
T *get_pointer() const {
return pointer;
}
private:
void set(T *pointer_new) noexcept {
if(pointer) {
CounterType *reference_counter = ((CounterType *) pointer) - 1;
if(--(*reference_counter) == 0) {
delete pointer;
}
}
if(pointer_new) {
CounterType *reference_counter_new = ((CounterType *) pointer_new) - 1;
(*reference_counter_new)++;
}
pointer = pointer_new;
}
};
#endif /* RCPOINTER_HPP */