|
a/src/utils/refcntr.h |
|
b/src/utils/refcntr.h |
1 |
#ifndef _REFCNTR_H_
|
1 |
#ifndef _REFCNTR_H_
|
2 |
#define _REFCNTR_H_
|
2 |
#define _REFCNTR_H_
|
3 |
|
3 |
|
4 |
// See Stroustrup C++ 3rd ed, p. 783
|
4 |
// See Stroustrup C++ 3rd ed, p. 783
|
5 |
template <class X> class RefCntr {
|
5 |
template <class X> class RefCntr {
|
6 |
X *rep;
|
6 |
X *rep;
|
7 |
int *pcount;
|
7 |
int *pcount;
|
8 |
public:
|
8 |
public:
|
9 |
X * operator->() {return rep;}
|
9 |
RefCntr()
|
|
|
10 |
: rep(0), pcount(0)
|
|
|
11 |
{}
|
|
|
12 |
RefCntr(X *pp)
|
10 |
RefCntr() : rep(0), pcount(new int(1)) {}
|
13 |
: rep(pp), pcount(new int(1))
|
11 |
RefCntr(X *pp) : rep(pp), pcount(new int(1)) {}
|
14 |
{}
|
12 |
RefCntr(const RefCntr &r) :rep(r.rep), pcount(r.pcount) { (*pcount)++;}
|
|
|
13 |
RefCntr& operator=(const RefCntr& r) {
|
15 |
RefCntr(const RefCntr &r)
|
14 |
if (rep == r.rep) return *this;
|
16 |
: rep(r.rep), pcount(r.pcount)
|
15 |
if (pcount && --(*pcount) == 0) {
|
17 |
{
|
16 |
delete rep;
|
18 |
if (pcount)
|
17 |
delete pcount;
|
19 |
(*pcount)++;
|
18 |
}
|
20 |
}
|
19 |
rep = r.rep;
|
21 |
RefCntr& operator=(const RefCntr& r)
|
20 |
pcount = r.pcount;
|
22 |
{
|
21 |
if (pcount)
|
23 |
if (rep == r.rep)
|
22 |
(*pcount)++;
|
|
|
23 |
return *this;
|
24 |
return *this;
|
|
|
25 |
if (pcount && --(*pcount) == 0) {
|
|
|
26 |
delete rep;
|
|
|
27 |
delete pcount;
|
|
|
28 |
}
|
|
|
29 |
rep = r.rep;
|
|
|
30 |
pcount = r.pcount;
|
|
|
31 |
if (pcount)
|
|
|
32 |
(*pcount)++;
|
|
|
33 |
return *this;
|
24 |
}
|
34 |
}
|
25 |
~RefCntr() {if (--(*pcount) == 0) {delete rep;delete pcount;}}
|
35 |
~RefCntr()
|
|
|
36 |
{
|
|
|
37 |
if (pcount && --(*pcount) == 0) {
|
|
|
38 |
delete rep;
|
|
|
39 |
delete pcount;
|
|
|
40 |
}
|
|
|
41 |
}
|
|
|
42 |
X *operator->() {return rep;}
|
26 |
int getcnt() const {return *pcount;}
|
43 |
int getcnt() const {return pcount ? *pcount : 0;}
|
27 |
const X * getptr() const {return rep;}
|
44 |
const X *getptr() const {return rep;}
|
28 |
};
|
45 |
};
|
29 |
|
46 |
|
30 |
|
47 |
|
31 |
#endif /*_REFCNTR_H_ */
|
48 |
#endif /*_REFCNTR_H_ */
|