skydoor
skydoor

Reputation: 25898

why weak_ptr can break cyclic reference?

I learnt a lot about weak_ptr working with share_ptr to break cyclic reference. How does it work? How to use that? Can any body give me an example? I am totally lost here.

One more question, what's a strong pointer?

Upvotes: 11

Views: 1589

Answers (2)

peterchen
peterchen

Reputation: 41116

A strong pointer holds a strong reference to the object - meaning: as long as the pointer exists, the object does not get destroyed.

The object does not "know" of every pointer individually, just their number - that's the strong reference count.

A weak_ptr kind of "remembers" the object, but does not prevent it from being destroyed. YOu can't access the object directly through a weak pointer, but you can try to create a strong pointer from the weak pointer. If the object does nto exist anymore, the resulting strong pointer is null:

shared_ptr<int> sp(new int);
weak_ptr<int> wp(sp);

shared_ptr<int> stillThere(wp);
assert(stillThere);  // yes, the original object still exists, we can now use it
stillThere.reset();  // releasing the strong reference

sp.reset();          // here, the object gets destroyed, 
                     // because there's only one weak_ptr left

shared_ptr<int> notReally(wp);
assert(!notReally);  // the object is destroyed, 
                     // you can't get a strong pointer to it anymore

Upvotes: 10

Tronic
Tronic

Reputation: 10430

It is not included in the reference count, so the resource can be freed even when weak pointers exist. When using a weak_ptr, you acquire a shared_ptr from it, temporarily increasing the reference count. If the resource has already been freed, acquiring the shared_ptr will fail.

Q2: shared_ptr is a strong pointer. As long as any of them exist, the resource cannot be freed.

Upvotes: 6

Related Questions