Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 973
skydoor Avatar asked Mar 03 '10 20:03

skydoor


People also ask

Can a weak_ptr point to a Unique_ptr?

You can implement weak_ptr which works correctly with unique_ptr but only on the same thread - lock method will be unnecessary in this case.

What is the difference between shared_ptr and weak_ptr?

shared_ptr maintains reference count for this propose. when all shared_ptr's pointing to resource goes out of scope the resource is destroyed. A weak_ptr is created as a copy of shared_ptr. It provides access to an object that is owned by one or more shared_ptr instances but does not participate in reference counting.

When should I use weak_ptr?

By using a weak_ptr , you can create a shared_ptr that joins to an existing set of related instances, but only if the underlying memory resource is still valid. A weak_ptr itself does not participate in the reference counting, and therefore, it cannot prevent the reference count from going to zero.

Is weak_ptr lock thread safe?

Note that the control block used by std::weak_ptr and std::shared_ptr is thread-safe: different non-atomic std::weak_ptr objects can be accessed using mutable operations, such as operator= or reset , simultaneously by multiple threads, even when these instances are copies or otherwise share the same control block ...


1 Answers

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
like image 180
peterchen Avatar answered Oct 20 '22 21:10

peterchen