| 1 | {{{ |
| 2 | #ifndef _SHAREDPTR_H_ |
| 3 | #define _SHAREDPTR_H_ |
| 4 | |
| 5 | #include "GaussNumber.h" |
| 6 | #define NULL 0 |
| 7 | |
| 8 | class Storage { |
| 9 | |
| 10 | private: |
| 11 | GaussNumber *p_obj; |
| 12 | int count; |
| 13 | |
| 14 | public: |
| 15 | Storage(GaussNumber *p_obj); |
| 16 | ~Storage(); |
| 17 | void increaseCount(); |
| 18 | void decreaseCount(); |
| 19 | GaussNumber *ptr() const; |
| 20 | bool isNull() const; |
| 21 | |
| 22 | }; |
| 23 | |
| 24 | |
| 25 | class shared_ptr { |
| 26 | |
| 27 | private: |
| 28 | Storage *storage; |
| 29 | |
| 30 | public: |
| 31 | shared_ptr(); |
| 32 | shared_ptr(GaussNumber *p_obj); |
| 33 | shared_ptr(const shared_ptr &sptr); |
| 34 | ~shared_ptr(); |
| 35 | const shared_ptr &operator=(const shared_ptr &sptr); |
| 36 | GaussNumber &operator*() const; |
| 37 | GaussNumber *operator->() const; |
| 38 | GaussNumber *ptr() const; |
| 39 | bool isNull() const; |
| 40 | |
| 41 | }; |
| 42 | |
| 43 | #endif |
| 44 | }}} |
| 45 | |
| 46 | {{{ |
| 47 | #include "shared_ptr.h" |
| 48 | |
| 49 | // Storage class definitions |
| 50 | |
| 51 | Storage::Storage(GaussNumber *p_obj) { |
| 52 | this->p_obj = p_obj; |
| 53 | count = 1; |
| 54 | } |
| 55 | |
| 56 | Storage::~Storage() { |
| 57 | if (p_obj != NULL) |
| 58 | delete p_obj; |
| 59 | } |
| 60 | |
| 61 | void Storage::increaseCount() { |
| 62 | count++; |
| 63 | } |
| 64 | |
| 65 | void Storage::decreaseCount() { |
| 66 | count--; |
| 67 | |
| 68 | if (count == 0) |
| 69 | delete this; |
| 70 | } |
| 71 | |
| 72 | GaussNumber *Storage::ptr() const { |
| 73 | return p_obj; |
| 74 | } |
| 75 | |
| 76 | bool Storage::isNull() const { |
| 77 | if (p_obj == NULL) |
| 78 | return true; |
| 79 | else |
| 80 | return false; |
| 81 | } |
| 82 | |
| 83 | // shared_ptr class definitions |
| 84 | |
| 85 | shared_ptr::shared_ptr() { |
| 86 | storage = new Storage(NULL); |
| 87 | } |
| 88 | |
| 89 | shared_ptr::shared_ptr(GaussNumber *p_obj) { |
| 90 | storage = new Storage(p_obj); |
| 91 | } |
| 92 | |
| 93 | shared_ptr::shared_ptr(const shared_ptr &sptr) { |
| 94 | storage = sptr.storage; |
| 95 | storage->increaseCount(); |
| 96 | } |
| 97 | |
| 98 | shared_ptr::~shared_ptr() { |
| 99 | storage->decreaseCount(); |
| 100 | } |
| 101 | |
| 102 | const shared_ptr &shared_ptr::operator=(const shared_ptr &sptr) { |
| 103 | sptr.storage->increaseCount(); |
| 104 | storage->decreaseCount(); |
| 105 | |
| 106 | storage = sptr.storage; |
| 107 | return *this; |
| 108 | } |
| 109 | |
| 110 | GaussNumber &shared_ptr::operator*() const { |
| 111 | return *storage->ptr(); |
| 112 | } |
| 113 | |
| 114 | GaussNumber *shared_ptr::operator->() const { |
| 115 | return storage->ptr(); |
| 116 | } |
| 117 | |
| 118 | GaussNumber *shared_ptr::ptr() const { |
| 119 | return storage->ptr(); |
| 120 | } |
| 121 | |
| 122 | bool shared_ptr::isNull() const { |
| 123 | return storage->isNull(); |
| 124 | } |
| 125 | }}} |