c++refcounting

Reference counting - internal references problem


I have implemented my own smart pointers, and everything worked fine, untill I realized a fatal flaw with my implementation. The problem was the fact that an object can have a smart pointer that potentially holds a reference to itself. the problem would be easy to avoid if this was a one layer problem - what could easly happen is a ref counted class would indirectly (through one of its members) holds a referenece to itself. this would mean that a object would never be removed deleted. Is there any way/method I could solve this?

simplest example:

class Derived : public Object {
public:
    static ref<Object> Create() { return ref<Object>(new Derived()); }

private:
    Derived() : m_ref(this) // m_ref now holds a reference to Derived instance
    {
        // SOME CODE HERE
    }
    ref<Object> m_ref;
};

Object is base class contains reference counter, ref is smart pointer that holds a reference to its assigned object


Solution

  • There is no easy way to handle this issue. It is a fundamental problem with reference counting.

    To build intuition as to why this is the case, note that the difficulty of detecting cycles of smart pointers is similar to the difficulty of dealing with the cycles. To detect cycles you need to be able to traverse the pointers from "root pointers". If you could do that, you could mark the ones you see during traversal. If you could mark them you could implement mark-and-sweep, which is garbage collection.