Parent: [8c9d44] (diff)

Child: [163096] (diff)

Download this file

refcntr.h    51 lines (47 with data), 960 Bytes

 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
#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)
{}
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;
}
~RefCntr()
{
if (pcount && --(*pcount) == 0) {
delete rep;
delete pcount;
}
}
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;}
};
#endif /*_REFCNTR_H_ */