Hello.
I have written a simple reference-counting smart pointer class template
called RefCountPtr<T>. It works in conjunction with another class,
ReferenceCounta ble, which is responsible for the actual counting. Here
is the latter's definition:
// --- Begin ReferenceCounta ble.h ----------
class ReferenceCounta ble
{
public:
virtual ~ReferenceCount able() {}
void incrementRefere nceCount() { count++; }
void decrementRefere nceCount() { count--; }
unsigned int referenceCount( ) const { return count; }
protected:
ReferenceCounta ble() : count(0) {}
private:
unsigned int count;
};
// --- End ReferenceCounta ble.h ----------
Classes whose objects are to be reference-counted must derive from
ReferenceCounta ble. E.g.:
// --- Begin Foo.h ----------
#include "ReferenceCount able.h"
class Foo : public ReferenceCounta ble
{
public:
void f() {}
};
// --- End Foo.h ----------
From now on, one can create instances of the smart pointer class and
use them as regular pointers. E.g.:
RefCountPtr<Foo pfoo = new Foo;
pfoo->f();
The idea of making the smart pointer behave like regular pointers is key
and is also the reason for this post. There is a situation where I have
found myself unable to make my smart pointers behave like regular ones.
It occurs when a given class holds RefCountPtr<Tas member variables.
For a regular pointer, one could do:
class Foo;
class Test
{
Foo* mFoo;
};
Therefore, I would like to be able to have:
#include "RefCountPtr.hp p"
class Foo;
class Test
{
RefCountPtr<Foo mFoo;
};
But, unfortunately, the compiler does not find it sufficient to know
that Foo is a class. Here is a relevant snippet of the /RefCountPtr<T>/
class template, showing its constructors, destructor and only member
variable:
// --- Begin snippet of RefCountPtr.hpp ----------
#include "ReferenceCount able.h"
template <class T>
class RefCountPtr
{
public:
RefCountPtr()
: object(0)
{
}
RefCountPtr(T* pointer)
: object(pointer)
{
if (object)
object->incrementRefer enceCount();
}
RefCountPtr(con st RefCountPtr& original)
: object(original .object)
{
if (object)
object->incrementRefer enceCount();
}
~RefCountPtr()
{
if (object)
{
object->decrementRefer enceCount();
if (object->referenceCount () == 0)
delete object;
}
}