### 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:

- addRef - Increments the object's reference count by one. Use this method when you create a new pointer that aliases a reference counted object.
- removeRef - Decrements the object's reference count by one. Use this method when you are finished using a pointer that aliases the object.
- count - Return the object's current reference count. This is useful when you want to implement copy-on-write semantics, because it allows you to find out if anyone else is using the object.

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