views:

194

answers:

2

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?

+6  A: 

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.

Tronic
+5  A: 

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
peterchen
Code sample complements your explanation very well.
Dr. Watson