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?
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.
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.
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.
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 ...
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With