Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding weak reference counter

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.

like image 789
Tracer Avatar asked Jul 16 '14 16:07

Tracer


People also ask

How does a weak reference work?

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.

What is a weak reference and how could it be useful to us?

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.

What are weak references difference between weak and strong references?

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.

What is the difference between strong and weak references C#?

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.


1 Answers

There are two objects associated with shared_ptr<T> & weak_ptr<T>:

  • the actual object (T)
  • the control block, that contains the shared and weak counters

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.

like image 162
nosid Avatar answered Sep 17 '22 20:09

nosid