Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I detect or avoid cyclic references with std::shared_ptr?

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?

like image 693
Tamás Szelei Avatar asked Aug 14 '26 18:08

Tamás Szelei


1 Answers

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.

like image 141
sellibitze Avatar answered Aug 16 '26 08:08

sellibitze



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!