-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsmart pointer.cpp
73 lines (58 loc) · 1.32 KB
/
smart 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
// code a smart pointer class.
#include <iostream>
#include <exception>
//#include <atomic> ==> This class is not thread-safe. So I should use atomic long for fCount.
using namespace std;
template<typename T>
class SmartPointer
{
T * fPtr;
long * fCount;
protected:
void remove() {
(*fCount)--;
if (*fCount == 0 && fPtr) {
delete fPtr;
delete fCount;
fCount = nullptr;
fPtr = nullptr;
cout << "deleted" << endl;
}
}
public:
SmartPointer(T * ptr) {
if (ptr == nullptr) throw "pointer is null.";
fPtr = ptr;
fCount = new long(1);
}
SmartPointer(const SmartPointer & r) {
fCount = r.fCount;
fPtr = r.fPtr;
(*fCount)++;
}
virtual ~SmartPointer() {
remove();
}
SmartPointer<T> & operator = (const SmartPointer<T> & r) {
if (r == this) return *this;
fPtr = r.fPtr;
fCount = r.fCount;
fCount++;
return *this;
}
void print() {
cout << fPtr << " : " << *fCount << endl;
}
};
int main()
{
{
SmartPointer<int> sp(new int(1));
SmartPointer<int> sp2 = sp;
SmartPointer<int> sp3 = new int(3);
sp.print();
sp2.print();
sp3.print();
}
return 0;
}