Reputation: 23961
I know that there is weak_ptr
to break the cycle, but that is a fix, after the problem is discovered. Is there a pattern or tool that can be used to either detect or avoid cyclic referencing?
Upvotes: 3
Views: 1973
Reputation: 16276
You can implement one, something like a wrapper over smart_ptr
which on creation stores this
pointer (e.g. by macro). Then build directed graph with edges from stored this
to object contained by shared_ptr
and detect any cycles, e.g. by topological sorting.
I would recommend this only for large code base with intensive shared_ptr
usage and inability to control all design aspects. For other cases just use @sellibitze recommendation.
Upvotes: 0
Reputation: 1701
I would strongly echo what sellibitze said and rethink the design. If what you really have is a one way ownership and simply observing in the opposite direction consider weak_ptr. This allows you to check if an object is alive, but does not keep the object alive simply because you have a pointer to it.
Upvotes: 1
Reputation: 28107
You avoid this by design. As Stephan T. Lavavej pointed out so nicely at the GoingNative2012 conference (you can check out the videos online), "ownership" is a directed acyclic graph, a DAG. There are no cycles in a DAG. If your ownership graph is not a DAG, your design is … questionable because A owning B and B owning A makes no sense. But shared_ptr is a "shared ownership pointer". The object or scope holding such a pointer owns the pointee. Try to think in terms of ownership graphs.
shared_ptr is not the right tool for every case. It's not supposed to allow you to code just like you'd do it in, say, Java where you don't have to think about ownership (much). It's supposed to provide automatic and deterministic cleanup. If you need a "non-owning" pointer, weak_ptr or a raw pointer is appropriate. Just make sure that the object a raw pointer points to stays alive long enough.
Upvotes: 6
Reputation: 153987
The obvious answer is not to use shared_ptr
to objects which
themselves might contain a shared_ptr
. shared_ptr
is somewhat
special, and should be used sparingly.
Upvotes: 2