-
Notifications
You must be signed in to change notification settings - Fork 0
/
shared_pointer.cpp
111 lines (96 loc) · 2.67 KB
/
shared_pointer.cpp
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#include <iostream>
template <typename T>
class sharedptr {
private:
T* resource;
int* counter; // count per resource
void increment_counter(){
if(counter) // it can be nullptr
(*counter)++;
}
void decrement_counter() {
if(counter){
(*counter)--;
if((*counter) == 0) {
if(resource) {
delete resource;
delete counter;
resource = nullptr;
counter = nullptr;
}
}
}
}
public:
sharedptr(T* ptr = nullptr) : resource(ptr), counter(new int(1)){
std::cout << "Contructor is called\n";
}
sharedptr <T> (const sharedptr <T>& ptr) {
resource = ptr.resource;
counter = ptr.counter;
increment_counter();
}
sharedptr <T>& operator= (const sharedptr <T>& ptr) {
if(this != &ptr) {
decrement_counter();
resource = ptr.resource;
counter = ptr.counter;
increment_counter();
}
return *this;
}
sharedptr <T> (sharedptr&& ptr) {
resource = ptr.resource;
counter = ptr.counter;
ptr.resource = nullptr;
ptr.counter = nullptr;
}
sharedptr<T>& operator= (sharedptr<T>&& ptr) {
if(this != &ptr) {
decrement_counter();
resource = ptr.resource;
counter = ptr.counter;
resource = nullptr;
counter = nullptr;
}
return *this;
}
void reset(T* newresource = nullptr) {
decrement_counter();
resource = newresource;
counter = new int(1);
}
int get_count() {
if(counter)
return (*counter);
return -1;
}
T* operator-> () {
return resource;
}
T& operator* () {
return (*resource);
}
T* get() {
return resource;
}
~sharedptr() {
decrement_counter();
}
};
int main() {
// requirements
sharedptr <int> ptr1; // default constructor
sharedptr <int> ptr2(new int(10)); // parameterized constructor
sharedptr <int> ptr3(ptr2); // copy constructor
ptr3 = ptr2; // assignment operator
sharedptr <int> ptr4(std::move(ptr1)); // move constructor
ptr2 = std::move(ptr3); // move copy assignment operator
ptr1.reset();
ptr1.reset(new int(200));
std::cout << *ptr1; // *operator overloading
// ptr1 -> func(); // ->operator constructor
ptr1.get(); // give the row pointer it points to
ptr1.get_count(); // number of objects pointing to the same resource
// destructor to free up the heap memory
}