A Generic Reference-Counted Pointer Class (4 Bubba)
I've implemented reference counting many times, but I've never done a generic implementation.
This was inspired by the discussions in this thread.
The main problem whith a generic reference-counted pointer class is knowing what to do once the reference count reaches zero. This may be calling delete for an allocated pointer, or performing some other cleanup routine.
This implementation uses templates and function pointers to get the job done.
Code:
#include <iostream>
#include <vector>
using namespace std;
template <class T>
class RefCountedPtr
{
public:
// prototype of function we will call when reference count reaches 0
typedef void (*ZeroRefFunc_t)(T*);
private:
ZeroRefFunc_t m_0RefFunc;
size_t *m_refs;
T *m_pointer;
// copy 'cpy' into '*this' and increment reference count
RefCountedPtr& copy(const RefCountedPtr &rcp)
{
m_refs = rcp.m_refs;
m_pointer = rcp.m_pointer;
(*m_refs)++;
return *this;
}//copy
public:
// construction
explicit RefCountedPtr(T *p, ZeroRefFunc_t f)
: m_0RefFunc(f), m_refs(new size_t(1)), m_pointer(p) {}
// destruction
~RefCountedPtr()
{
if (--(*m_refs) == 0)
{
delete m_refs;
m_refs = 0;
m_0RefFunc(m_pointer);
}//if
}//destructor
// copy semantics
RefCountedPtr(const RefCountedPtr &rcp) {copy(rcp);}
RefCountedPtr& operator=(const RefCountedPtr &rcp) {return copy(rcp);}
// pointer access
T* operator->() {return m_pointer;}
private:
RefCountedPtr(); // must use explicit constructor
};//RefCountedPtr
struct A
{
A() {cout << "constructor" << endl;}
~A() {cout << "destructor" << endl;}
};//A
void DeleteA(A *p) {delete p;}
int main()
{
RefCountedPtr<A> rcp(new A, &DeleteA);
vector<RefCountedPtr<A> > v1;
v1.push_back(rcp);
v1.push_back(rcp);
v1.push_back(rcp);
v1.push_back(rcp);
// make a copy of v1
vector<RefCountedPtr<A> > v2 = v1;
// when v1 and v2 go out of scope, the last instance of RefCountedPtr<A>
// will call DeleteTest() for us
return 0;
}//maim
gg