Using Reference Counted Objects

IMRefCounted cannot be used directly; it must be subclassed. To enforce this, its constructors and destructor are all declared protected.

When using an IMRefCounted subclass, you can call the following public methods:

When you are using IMRefCounted objects with raw C++ pointers, you must remember to call addRef and removeRef at the appropriate times, as in the following example:

class Foo : public IMRefCounted {
    ...
};
...
{
    Foo *fooPtr = new Foo();
    fooPtr->addRef();       // Added a pointer, so increase the ref count
    functionCall(fooPtr);   // Could bump the ref count if it needs to.
    fooPtr->removeRef();    // Finished using fooPtr
}

To implement copy-on-write semantics for a class, you typically use an internal implementation object that is reference counted and copied only when needed. For example:

class Bar {
  public:
    void setValue(int i);
  private:
    BarImp *fImp;     // BarImp is IMRefCounted
};

void Bar::setValue(int i)
{
    if (fImp->count() > 1) {
         // My implementation is shared, so make my own private copy
         BarImp *temp = new BarImp(*fImp);
         fImp->removeRef();
         fImp = temp;
         fImp->addRef();
    }
    fImp->setValue(i);
}

Subclassing

When creating your own subclass of IMRefCounted, the only real issue is whether you want to force clients to use your class in a reference-counted manner, or whether you want to allow them to use the class with normal stack or heap allocation semantics. If you want to force clients to do reference counting, make the destructor protected. This will prevent clients from allocating your class on the stack and from deleting heap objects of that class; they will instead have to call the removeRef method that it inherits from IMRefCounted.



Using Counted Pointers


Counted Pointers
Reference Counted Objects