Home Forum RSS PGP Alerts Links (D) |
![]() |
Thursday February 16, 2017 |
Reference counting pointer templates Comment on this article
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.
|
TOP |