Tracking down shared_ptr cyclic dependencies

Started by
2 comments, last by Shannon Barber 18 years, 9 months ago
I'm using boost::shared_ptr for a project with a very complex set of object dependencies. After adding every feature I used to check for memory leaks using VC's _CrtDumpMemoryLeaks(). This way I could see leaks early and had a good idea of where the cyclic dependencies may be. Unfortunately I haven't rant this test for quite some time. I am now stuck with with a complex dependency graph and not the slighest idea of where the cyclic dependency may be introduced. Does anyone have any suggestions on how to debug this?
Advertisement
Without knowing more about your project, the only recommendation I can come up with is to carefully evaluate things to see if any of those shared_ptrs can be replaced by weak_ptrs. That may be enough to break the dependency.
Well, after spending some time on this I've managed to track down the offending piece. There is a place where two objects have a cyclic dependency. The problem is that getting rid of this dependency isn't trivial. If I have two objects named A and B, in some cases A should 'own' B and in other cases B should 'own' A. Replacing one or the other shared_ptr with a weak_ptr isn't an option as it would break the logic.

I'm trying to come up with a good ownership rule that will break the dependency but it certainly isn't easy. If anyone cares, I'm implementing a context/function relationship in a Lisp interpreter. Sometimes a function holds a reference to the context (closures, for example), at other times the context holds the reference to the function (indirectly through a bound symbol).

I have to think about this more. I'll post the solution as soon as I come up with one. In the meantime if anyone has suggestions they're very welcome.
The object needs both a weak_ptr and shared_ptr. You always set the weak_ptr and use the weak_ptr in all member functions, you set the shared_ptr iff it owns the object so it will destroy it.
- The trade-off between price and quality does not exist in Japan. Rather, the idea that high quality brings on cost reduction is widely accepted.-- Tajima & Matsubara

This topic is closed to new replies.

Advertisement