Let me repeat your question: "My question is, how do circular data structures make the reference count higher than zero, please kindly ask for an example using a C ++ program. How can the problem be solved with weak_ptrs again with an example please."
The problem arises with such C ++ code (conceptually):
class A { shared_ptr<B> b; ... }; class B { shared_ptr<A> a; ... }; shared_ptr<A> x(new A);
To answer the second part of your question: it is mathematically impossible to count links for loop processing. Thus, a weak_ptr (which is basically just a stripped down version of shared_ptr ) cannot be used to solve the loop problem - the programmer solves the loop problem.
To solve this problem, the programmer must know the relationship of ownership between objects or must invent a relationship of ownership if such ownership does not exist naturally.
The above C ++ code can be changed so that A owns B:
class A { shared_ptr<B> b; ... }; class B { weak_ptr<A> a; ... }; shared_ptr<A> x(new A); // +1 x->b = new B; // +1 x->b->a = x; // No +1 here // Ref count of 'x' is 1. // Ref count of 'x->b' is 1. // When 'x' leaves the scope, its ref count will drop to 0. // While destroying it, ref count of 'x->b' will drop to 0. // So both A and B will be deallocated.
The critical question is: can weak_ptr be used if the programmer cannot determine the ownership relationship and cannot establish any static ownership due to lack of privilege or lack of information?
Answer: If ownership among objects is fuzzy, weak_ptr cannot help. If there is a loop, the programmer must find it and break it. An alternative is to use a programming language with full garbage collection (e.g. Java, C #, Go, Haskell) or use a conservative garbage collector (= imperfect) that works with C / C ++ (e.g. Boehm GC).
user811773 Sep 19 '11 at 15:48 2011-09-19 15:48
source share