How does a reference-counting smart pointer's reference counting work?
I've seen two different non-intrusive approaches to this:
- The smart pointer allocates a small block of memory to contain the reference counter. Each copy of the smart pointer then receives a pointer to the actual object and a pointer to the reference count.
- In addition to an object pointer, each smart pointer contains a previous and next pointer, thereby forming a doubly-linked list of smart pointers to a particular object. The reference count is implicit in the list. When a smart pointer is copied, it adds itself to the list. Upon destruction, each smart pointer removes itself from the list. If it's the last one in the list it then frees the referenced object as well.
If you go here and scroll to the bottom, there is an excellent diagram which explains these methods much more clearly.
Creating a memory leak with reference-counting smart pointers is very easy. Just create any graph-like structure of objects that has a cycle in the graph. The objects in the cycle will prevent each other from being released. This can't be resolved automatically - for example, when you create a double-link list you have to take care of never removing more than one object at a time.
Each smart pointer object contains a shared reference count - one for every raw pointer.
You could take a look at this article. This implementation stores these in a separate object which is copied around. You could also take a look at boost's documentation or take a look at the Wikipedia article on smart pointers.