When creating shared_ptr it's manager object uses strong & weak reference counters. I understand that by using strong reference counter shared_ptr knows when to deallocate the managed object but I don't understand why is it using weak reference counter.
A weakly referenced object is cleared by the Garbage Collector when it's weakly reachable. Weak reachability means that an object has neither strong nor soft references pointing to it. The object can be reached only by traversing a weak reference.
A weak reference allows the garbage collector to collect an object while still allowing an application to access the object. If you need the object, you can still obtain a strong reference to it and prevent it from being collected.
A weak reference is just a pointer to an object that doesn't protect the object from being deallocated by ARC. While strong references increase the retain count of an object by 1, weak references do not. In addition, weak references zero out the pointer to your object when it successfully deallocates.
The difference between a weak and a strong reference to an object is that while the former still allows the garbage collector to reclaim the memory occupied by that object, a strong reference to an object doesn't allow the garbage collector to reclaim the memory occupied by that object if the object is reachable.
There are two objects associated with shared_ptr<T>
& weak_ptr<T>
:
T
)The actual object will be destroyed, if the shared counter reaches 0
. But the control block has to stay alive as long as there are shared or weak pointers, i.e. the control block will be deleted as soon as both the shared and weak counter are 0
.
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