add release() method

This commit is contained in:
dockes 2009-08-13 06:34:32 +00:00
parent 9b44f94629
commit 18a2454a03

View File

@ -7,37 +7,43 @@ template <class X> class RefCntr {
int *pcount; int *pcount;
public: public:
RefCntr() RefCntr()
: rep(0), pcount(0) : rep(0), pcount(0)
{} {}
explicit RefCntr(X *pp) explicit RefCntr(X *pp)
: rep(pp), pcount(new int(1)) : rep(pp), pcount(new int(1))
{} {}
RefCntr(const RefCntr &r) RefCntr(const RefCntr &r)
: rep(r.rep), pcount(r.pcount) : rep(r.rep), pcount(r.pcount)
{ {
if (pcount) if (pcount)
(*pcount)++; (*pcount)++;
} }
RefCntr& operator=(const RefCntr& r) RefCntr& operator=(const RefCntr& r)
{ {
if (rep == r.rep) if (rep == r.rep)
return *this; return *this;
if (pcount && --(*pcount) == 0) { if (pcount && --(*pcount) == 0) {
delete rep; delete rep;
delete pcount; delete pcount;
} }
rep = r.rep; rep = r.rep;
pcount = r.pcount; pcount = r.pcount;
if (pcount) if (pcount)
(*pcount)++; (*pcount)++;
return *this; return *this;
}
void release()
{
if (pcount && --(*pcount) == 0) {
delete rep;
delete pcount;
}
rep = 0;
pcount = 0;
} }
~RefCntr() ~RefCntr()
{ {
if (pcount && --(*pcount) == 0) { release();
delete rep;
delete pcount;
}
} }
X *operator->() {return rep;} X *operator->() {return rep;}
X *getptr() const {return rep;} X *getptr() const {return rep;}