Menu Categories Author

Nubis Novem

Consulting On Cloud Nine

Reference counting in C++

I have tried recently to use the C++ 11 version of the reference counting, the class std::shared_ptr. And I must say, it is crap. Utter and complete crap.

Their problem is that they are trying to do reference counting to any structures at all, without storing the reference counter in the structure itself. The consequence is that you absolutely can not mix the shared_ptr and pointers. Once you store a pointer in a shared_ptr , you have to refer to it by shared_ptr, and assign the shared_ptr values to each other. If you take a pointer and store it in another shared_ptr, you end up with two reference counters to the same structure, and end up with the memory corruption. And it is way too easy to make this mistake. It is really not usable.

In my Triceps project (see http://triceps.sf.net) I made my own version of the reference counter, the Autoref template. It is way, way, way better and safer to use. It works differently: the reference counter is stored in the class being pointed to, and that class provides the methods incref() and decref() to modify the reference counter. Generally these come from a base class, and I made two kinds of base classes: Starget for the single-threaded references and Mtarget for the multithreading-safe ones.

Leave a Reply

Your email address will not be published. Required fields are marked *