c++garbage-collectionshared-ptrreference-counting

How to detect cycles when using shared_ptr


shared_ptr is a reference counting smart pointer in the Boost library.

The problem with reference counting is that it cannot dispose of cycles. I am wondering how one would go about solving this in C++.

Please no suggestions like: "don't make cycles", or "use weak_ptr".

Edit

I don't like suggestions that say to just use a weak_ptr because obviously if you know you will create a cycle, then you wouldn't have a problem. You also cannot know you will have a cycle at compile time if you generate shared_ptrs at runtime.

So please, self delete answers that use weak_ptr in them because I specifically asked not to have those kind of answers...


Solution

  • I haven't found a much better method than drawing large UML graphs and looking out for cycles.

    To debug, I use an instance counter going to the registry, like this:

    template <DWORD id>
    class CDbgInstCount
    {
    public:
    #ifdef _DEBUG
       CDbgInstCount()   { reghelper.Add(id, 1); }
       CDbgInstCount(CDbgInstCount const &) {  reghelper.Add(id, 1); }
       ~CDbgInstCount()  { reghelper.Add(id, -1); }
    #else
    #endif
    };
    

    I just ned to add that to the classes in question, and have a look at the registry.

    (The ID, if given as e.g. 'XYZ!' will be converted to a string. Unfortunately, you can't specify a string constant as template parameter)