Smart Pointers
Many objects in Objective Views are reference counted. An object that is reference counted knows how many objects reference it. When an object’s reference count reaches zero, there are no longer any other objects that depend on it and the object can delete itself. All objects that are reference counted implement the IODObject interface to keep track of their references.
Reference counting can be prone to error. If the count is off, objects can be left in memory when the application exits, or they can be deleted before other objects are finished with them. To automate reference counting, smart pointers are used in many places throughout Objective Views.
The SmartPtr template encapsulates pointers to objects that support the functions AddRef() and Release(). The IODObject interface defines AddRef() and Release(), so SmartPtr works with any object that implements the IODObject interface. The SmartPtr automatically increments the reference count by calling AddRef() whenever it is assigned a pointer. The SmartPtr can be assigned a pointer through its constructor or through the assignment operator. When the SmartPtr is destroyed or when it is assigned a new pointer value, it decrements the reference count by calling Release(). The SmartPtr class overrides the pointer reference operator-> so that using the pointer value it encapsulates is transparent. In other words, the SmartPtr can be used as though it is a pointer value. Consider smart pointers as pointer objects that replace the standard pointers in C++.