Smart Pointers in C++
Posted by Kaya Kupferschmidt • Saturday, July 9. 2005 • Category: C++
If one is building a complex piece of software with many objects, almost automatically the problem of shared objects arises. That means there exist objects which do not only have one owner, but multiple owners instead - they are shared objects. The difficult question with shared objects is their lifecycle. Once an object is created and bound to different owners, it is not clear any more how and when the object should be removed from memory.
One common approach to this problem is reference counting, that is, each shared object contains a reference counter that is incremented each time the object is bound to a new owner and it is decremented as soon as one of its owners wants to release the object. Using C++ templates the reference counting mechanism can be easily automated by introducing so called smart pointers. The following snippets of code implement both an object with reference counting (which in turn can be used as a base class for many classes) and the basic ideas how to implement a shared pointer.
One common approach to this problem is reference counting, that is, each shared object contains a reference counter that is incremented each time the object is bound to a new owner and it is decremented as soon as one of its owners wants to release the object. Using C++ templates the reference counting mechanism can be easily automated by introducing so called smart pointers. The following snippets of code implement both an object with reference counting (which in turn can be used as a base class for many classes) and the basic ideas how to implement a shared pointer.


