In shared_ptr smart pointer, reference counting is used. However, reference counting has a problem, that it can’t break cycles of reference.
I have four questions with this issue.
1) Could anybody offer me one snippet in which the cycles of reference happened?
2) If it can’t break cycles of reference, how does RCSP guarantee success resource manage? Is there any way to break the cycles with 3rd party product?
3) Is there anyway to avoid the cycles of reference?
4) How about other smart pointers? How does they deal with the source manage? For example, share_ptr, scope_ptr?
Many thanks!
The usual way to avoid cycles is to use weak references in any one point of the cycle.
shared_ptrhas a companion type,weak_ptr, which is designed for this purpose.Which part of the cycle to weaken is a matter of design. In designs where “parent” objects own “children”, then the reference from parent to child should be strong (
shared_ptr), and the reference from child back to parent should be weak (weak_ptr).