What solutions are there for circular references?

OB OB picture OB OB · Jul 1, 2009 · Viewed 9.3k times · Source

When using reference counting, what are possible solutions/techniques to deal with circular references?

The most well-known solution is using weak references, however many articles about the subject imply that there are other methods as well, but keep repeating the weak-referencing example. Which makes me wonder, what are these other methods?

  • I am not asking what are alternatives to reference counting, rather what are solutions to circular references when using reference counting.

  • This question isn't about any specific problem/implementation/language rather a general question.

Answer

Randolpho picture Randolpho · Jul 1, 2009

I've looked at the problem a dozen different ways over the years, and the only solution I've found that works every time is to re-architect my solution to not use a circular reference.

Edit:

Can you expand? For example, how would you deal with a parent-child relation when the child needs to know about/access the parent?OB OB

As I said, the only good solution is to avoid such constructs unless you are using a runtime that can deal with them safely.

That said, if you must have a tree / parent-child data structure where the child knows about the parent, you're going to have to implement your own, manually called teardown sequence (i.e. external to any destructors you might implement) that starts at the root (or at the branch you want to prune) and does a depth-first search of the tree to remove references from the leaves.

It gets complex and cumbersome, so IMO the only solution is to avoid it entirely.