-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSmartPointer.cpp
More file actions
98 lines (79 loc) · 1.88 KB
/
Copy pathSmartPointer.cpp
File metadata and controls
98 lines (79 loc) · 1.88 KB
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
//
// Created by Edgar Eggert on 12.04.21.
//
#include <iostream>
template<typename T>
class SmartPointer {
private:
T* heapObject;
int* refCount;
void release() {
if(heapObject != nullptr) {
(*refCount)--;
if(*refCount == 0) {
delete heapObject;
delete refCount;
}
}
}
void copy(const SmartPointer<T>& other) {
// Copy the pointers to the referenced object and its reference count
heapObject = other.heapObject;
refCount = other.refCount;
if(heapObject != nullptr) {
(*refCount)++;
}
}
public:
SmartPointer() {
heapObject = nullptr;
refCount = nullptr;
}
SmartPointer(T* heapObject) : heapObject(heapObject){
refCount = new int(1);
}
SmartPointer<T>& operator=(SmartPointer<T> & other){
if (&other != this){
release();
copy(other);
}
return *this;
}
SmartPointer(SmartPointer<T> & other){
copy(other);
}
int getRefCount() const {
if (this->refCount != nullptr){
return *refCount;
}
return 0;
}
T & operator*() {
return *(this->heapObject);
}
T* operator->(){
return this->heapObject;
}
~SmartPointer() {
release();
}
};
class TestClass1 {
public:
virtual void print() { std::cout << "TestClass1 at address " << this << '\n'; }
};
class DerivedClass : public TestClass1 {
public:
virtual void print() { std::cout << "DerivedClass at address " << this << '\n'; }
};
class TestClass2 {
public:
int number;
void print() { std::cout << "TestClass2 at address " << this << '\n'; }
};
class PtrLoop {
public:
int number;
SmartPointer<PtrLoop> self_ptr;
void print() { std::cout << "PtrLoop at address " << this << '\n'; }
};