-
Notifications
You must be signed in to change notification settings - Fork 0
/
countedpointer.h
129 lines (85 loc) · 2 KB
/
countedpointer.h
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
//
// Created by phtran on 07/05/2016.
//
#ifndef FRONTEND_COUNTEDPOINTER_H
#define FRONTEND_COUNTEDPOINTER_H
template<class T>
class counted_ptr
{
public:
typedef T element_type;
explicit counted_ptr( T *p = 0 )
: itsCounter( 0 )
{
if ( p ) {
itsCounter = new counter(p);
}
}
~counted_ptr()
{
release();
}
counted_ptr( const counted_ptr &r ) throw()
{
acquire( r.itsCounter );
}
counted_ptr& operator=( const counted_ptr &r )
{
if (this != &r) {
release();
acquire(r.itsCounter);
}
return *this;
}
#if 0
#ifndef NO_MEMBER_TEMPLATES
template <class Y> friend class counted_ptr<Y>;
template <class Y> counted_ptr(const counted_ptr<Y>& r) throw()
{acquire(r.itsCounter);}
template <class Y> counted_ptr& operator=(const counted_ptr<Y>& r)
{
if (this != &r) {
release();
acquire(r.itsCounter);
}
return *this;
}
#endif // NO_MEMBER_TEMPLATES
#endif
T& operator*() const throw() { return *itsCounter->ptr; }
T* operator->() const throw() { return itsCounter->ptr; }
T* get() const throw() { return itsCounter ? itsCounter->ptr : 0; }
bool unique() const throw()
{
return ( itsCounter ? itsCounter->count == 1 : true );
}
private:
struct counter
{
counter( T *p = 0,
unsigned c = 1 )
: ptr( p )
, count(c)
{ }
T *ptr;
unsigned count;
} *itsCounter;
void acquire( counter *c ) throw()
{
itsCounter = c;
if ( c ) {
++c->count;
}
}
void release()
{
if ( itsCounter ) {
if (--itsCounter->count == 0) {
//delete itsCounter->ptr;
//delete itsCounter;
}
itsCounter = 0;
}
}
};
#endif //FRONTEND_COUNTEDPOINTER_H