-
Notifications
You must be signed in to change notification settings - Fork 0
/
reference_ptr.cpp
80 lines (67 loc) · 1.15 KB
/
reference_ptr.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
74
75
76
77
78
79
80
#include <iostream>
template<typename T>
class Reference
{
public:
typedef T value_type;
public:
Reference(T *ref):
m_referenced(ref)
{
m_count = new size_t;
*m_count = 1;
}
Reference(const Reference& rhs):
m_referenced(rhs.m_referenced),
m_count(rhs.m_count)
{
increase_count();
}
Reference& operator=(const Reference& rhs)
{
decrease_count();
m_referenced = rhs.m_referenced;
m_count = rhs.m_count;
increase_count();
}
T& operator*() const
{
return *m_referenced;
}
T* operator->() const
{
return m_referenced;
}
~Reference()
{
decrease_count();
}
private:
void decrease_count()
{
--(*m_count);
if(!*m_count)
{
delete m_referenced;
delete m_count;
}
}
void increase_count()
{
++(*m_count);
}
private:
T *m_referenced;
size_t *m_count;
};
struct Foo
{
int a;
};
int main()
{
Reference<int> a((new int));
Reference<int> b((new int));
a = b;
return 0;
}