1 | #include "shared_ptr.h" |
---|
2 | |
---|
3 | // Storage class definitions |
---|
4 | |
---|
5 | Storage::Storage(GaussNumber *p_obj) { |
---|
6 | this->p_obj = p_obj; |
---|
7 | count = 1; |
---|
8 | } |
---|
9 | |
---|
10 | Storage::~Storage() { |
---|
11 | if (p_obj != NULL) |
---|
12 | delete p_obj; |
---|
13 | } |
---|
14 | |
---|
15 | void Storage::increaseCount() { |
---|
16 | count++; |
---|
17 | } |
---|
18 | |
---|
19 | void Storage::decreaseCount() { |
---|
20 | count--; |
---|
21 | |
---|
22 | if (count == 0) |
---|
23 | delete this; |
---|
24 | } |
---|
25 | |
---|
26 | GaussNumber *Storage::ptr() const { |
---|
27 | return p_obj; |
---|
28 | } |
---|
29 | |
---|
30 | bool Storage::isNull() const { |
---|
31 | if (p_obj == NULL) |
---|
32 | return true; |
---|
33 | else |
---|
34 | return false; |
---|
35 | } |
---|
36 | |
---|
37 | // shared_ptr class definitions |
---|
38 | |
---|
39 | shared_ptr::shared_ptr() { |
---|
40 | storage = new Storage(NULL); |
---|
41 | } |
---|
42 | |
---|
43 | shared_ptr::shared_ptr(GaussNumber *p_obj) { |
---|
44 | storage = new Storage(p_obj); |
---|
45 | } |
---|
46 | |
---|
47 | shared_ptr::shared_ptr(const shared_ptr &sptr) { |
---|
48 | storage = sptr.storage; |
---|
49 | storage->increaseCount(); |
---|
50 | } |
---|
51 | |
---|
52 | shared_ptr::~shared_ptr() { |
---|
53 | storage->decreaseCount(); |
---|
54 | } |
---|
55 | |
---|
56 | const shared_ptr &shared_ptr::operator=(const shared_ptr &sptr) { |
---|
57 | sptr.storage->increaseCount(); |
---|
58 | storage->decreaseCount(); |
---|
59 | |
---|
60 | storage = sptr.storage; |
---|
61 | return *this; |
---|
62 | } |
---|
63 | |
---|
64 | GaussNumber &shared_ptr::operator*() const { |
---|
65 | return *storage->ptr(); |
---|
66 | } |
---|
67 | |
---|
68 | GaussNumber *shared_ptr::operator->() const { |
---|
69 | return storage->ptr(); |
---|
70 | } |
---|
71 | |
---|
72 | GaussNumber *shared_ptr::ptr() const { |
---|
73 | return storage->ptr(); |
---|
74 | } |
---|
75 | |
---|
76 | bool shared_ptr::isNull() const { |
---|
77 | return storage->isNull(); |
---|
78 | } |
---|