examples_from_lect3: shared_ptr.cpp

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