I think my question is similar to shared_ptr and weak_ptr differences, but I'm interested in seeing how they work together rather than a list of differences.
Wikipedia's page on shared_ptr and weak_ptr state a weak_pointer
can be used to solve a circular dependency problem, and it gives an example:
std::shared_ptr<int> p1(new int(5));
std::weak_ptr<int> wp1 = p1; //p1 owns the memory.
{
std::shared_ptr<int> p2 = wp1.lock(); //Now p1 and p2 own the memory.
if(p2) //Always check to see if the memory still exists
{
//Do something with p2
}
} //p2 is destroyed. Memory is owned by p1.
p1.reset(); //Memory is deleted.
std::shared_ptr<int> p3 = wp1.lock(); //Memory is gone, so we get an empty shared_ptr.
if(p3)
{
//Will not execute this.
}
But I don't see a circular dependency, so I don't understand how weak_pointer
solves the problem.
I would have expected to see some object a
pointing to an object b
, and b
somehow pointing back to a
(with a weak_ptr
shimmed in between one of the directed graph edges to break the chain).
Is the example good and my thinking bad? Or is there a better example of the problem and solution?