Download 1 Introduction
Transcript
5.3 The class ObjectReference
For each user-created object we must add a little header with the reference counting information and the
ways to increase, decrease and retrieve the reference count. The way this is done is to make it a super-class
of all the user constructed classes. It is made this way because it imposes the least effort for the user, he
only has to publicly inherit from the class and then never bother again.
Figure 3. ObjectReference
ObjectReference
UserObject
We call the class ObjectReference and it’s a very simple class. Here is an example of how the declaration
of class ObjectReference looks like:
class ObjectReference
{
public:
usigned int referenceCount() const;
void increaseReferenceCount();
void decreaseReferenceCount();
virtual ~ObjectReference();
protected:
ObjectReference();
private:
unsigned int referenceCountValue;
};
As we can see the constructor is declared as a protected member. This will guarantee that an object of that
class can only be created by a publicly inherited sub-class. This make it impossible to instantiate an object
of class ObjectReference itself because we will get errors during compilation if we try. Instead we must
publicly inherit from the ObjectReference class. This will encourage the user to inherit the class. Also the
destructor is declared to be virtual. This will guarantee that the destructors in will be called from the bottom
and up in an inheritance tree.
The methods of the class is described here:
ObjectReference :: ObjectReference()
{
referenceCountValue = 0;
}
The reference count is set to zero when an object is created.
unsigned int ObjectReference :: referenceCount() const
{
return referenceCountValue;
}
The referenceCount method make it possible for the SmartPointer class to read how many references to the
object that exists.
void ObjectReference :: increaseReferenceCount()
{
++referenceCountValue;
}
The increase method just increases the reference count by one.
7