引用计数的实现:
template <class T>
class ReferenceCount
{
public:
explicit ReferenceCount(T* p):ptr(p),count(new int(1)){}
ReferenceCount(const ReferenceCount<T>& p) throw() : ptr(p.ptr),count(p.count)
{
++*count;
}
ReferenceCount<T>& operator = (const ReferenceCount<T>& p)
{
if(this != &p)
{
dispose();
ptr = p.ptr;
count = p.count;
++*count;
}
return *this;
}
T* operator->() throw()
{
return ptr;
}
T& operator *() throw()
{
return *ptr;
}
private:
void dispose()
{
if(0 == --*count)
{
delete ptr;
delete count;
}
}
private:
T* ptr;
int* count;
};
数个群集共享相同的数据元素,可以运用引用计数。如下:
typedef ReferenceCount<std::string> stringPtr;
char *strings[] ={"my","school","is","hdu"};
std::deque<ReferenceCount<std::string> > coll1;
std::deque<ReferenceCount<std::string> > coll2;
for(int i = 0;i < 4;++i)
{
stringPtr tempStringPtr(new std::string(strings[i]));
coll1.push_back(tempStringPtr);
coll2.push_back(tempStringPtr);
}
这样coll1和coll2中共享同一份数据,每个元素的引用计数都是2.