Smart PointersWhat is a pointer? A definition may be a variable which holds the address of some memory location. A more interesting way to define anything in programming is by its attributes and actions. A pointer has the attribute of holding an address, and has several actions: (assumes: int* p)
A smart pointer is a type that provides all of the above requirements, and perhaps does something extra which is useful. In this case, a smart pointer will make sure to call the addRef() subRef() for us, freeing us from worrying. When should the reference counting be changed for an object? When ever someone acquires a pointer to the object, the counter should be incremented. When ever someone lets go of a pointer to the object, the counter should be decremented. The last one to let go of the pointer should also delete the object. Using C++ features, here is a template class for such a smart pointer. It assumes the template parameter provides the reference counting operations.
The constructors store the pointers and call addRef() to increment the counter, due to this new pointer. The destructor cleans up the counter. This is obviously not enough, since the smart pointer can be changed by assignment
Note that the operator first decrements the counter for the old pointer, and then assigns the new pointer and increments its counter. Now several operators to provide the pointer actions, and some useful conversions:
I recommend removing the last operator, to avoid problems. Use it only if absolutely necessary. Here is the implementation of the private part of the class, which modifies the counter:
UsageUsing these pointers means simply to replace the declaration of the pointer:
All the rest of the code can remain the same, as this type provides the same semantics as a regular pointer. |
|||||||||||||||||||