Thursday February 16, 2017

Reference counting pointer templates

Comment on this article

Reference counted pointer templateReference counting pointer templates (some call them reference counted pointers for some agrammatical reason) are a special type of smart pointer templates in C++, especially suited for the application of the facade pattern in the design of COM servers. (If "facade pattern" doesn't ring a bell, you're in urgent need of "Design Patterns". That's a book, by the way.) When such COM servers make use of containers, it's much easier to store non-COM objects as pointer objects in those containers and only wrap them in COM-objects once they need to be delivered to the COM client. Reference counted pointer templates, as distinct from other C++ pointer templates, make it easy to just use a single instance of a data object that is then both kept in a container (STL or otherwise) and at the same time given back to the COM client.

Reference counting can be implemented using several different methods in templates. On the one hand, you can derive the objects you want counted from a template base class. On the other hand, you can implement the counting mechanism as a lightweight proxy so you don't need to touch the code for the class you're counting. Both these implementations are provided in document and code below.

Other considerations are to avoid mutual holds between objects. This happens when two objects hold reference counted pointers to each other and thus keep each other alive indefinitely. Introducing weak pointers can solve this problem. One of the templates below also implement weak pointer templates for this use. Note that weak pointers on their own can be a bit hard to manage right. They should be intimately tied into the strong pointers, in this case the "regular" reference counting pointer template. In the code,  the main template itself provides for weak pointers by a special member function getwptr(). The idea with this is that you should only create weak pointers on objects that already have at least one strong pointer.

I've used these templates in production code for a while now, and I'm very happy with them. Not with the lightweight proxy thing, as you'll notice in the article text, but with the base class type templates.

Any improvements you may have for my reference counting pointer templates would be very welcome.

Note: a shorter version of the text and code was published in the June 2001 issue of Windows Developers Journal

Comment on this article

TOP