Child: [4080b4] (diff)

Download this file

refcntr.h    58 lines (54 with data), 1.2 kB

 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
#ifndef _REFCNTR_H_
#define _REFCNTR_H_
// See Stroustrup C++ 3rd ed, p. 783
template <class X> class RefCntr {
X *rep;
int *pcount;
public:
RefCntr()
: rep(0), pcount(0)
{}
explicit RefCntr(X *pp)
: rep(pp), pcount(new int(1))
{}
RefCntr(const RefCntr &r)
: rep(r.rep), pcount(r.pcount)
{
if (pcount)
(*pcount)++;
}
RefCntr& operator=(const RefCntr& r)
{
if (rep == r.rep)
return *this;
if (pcount && --(*pcount) == 0) {
delete rep;
delete pcount;
}
rep = r.rep;
pcount = r.pcount;
if (pcount)
(*pcount)++;
return *this;
}
void release()
{
if (pcount && --(*pcount) == 0) {
delete rep;
delete pcount;
}
rep = 0;
pcount = 0;
}
~RefCntr()
{
release();
}
X *operator->() {return rep;}
X *getptr() const {return rep;}
const X *getconstptr() const {return rep;}
int getcnt() const {return pcount ? *pcount : 0;}
bool isNull() const {return rep == 0;}
bool isNotNull() const {return rep != 0;}
};
#endif /*_REFCNTR_H_ */