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.
3 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.
8 Comments
weak_ptr necessary? Or why is a counter for weak_ptrs necessary?Both weak and strong pointers hold a pointer to data, and a pointer to a reference count block.
When you try to convert a weak pointer to a strong pointer, you add a new strong count. If it incremented from 0, you know that the data had already been destroyed, so you fail. This requires access to the reference count block.
As such, the lifetime of the reference count block has to exceed the lifetime of all outstanding weak pointers.
This is ensured by reference counting the reference count block with a weak reference count. This reference count, when reduced to zero by the last outstanding strong or weak reference going out of scope, causes the smart pointer to destroy the reference count block.
Comments
weak_ptr is used for things that need a handle to the heap-object in question, but don't want to claim any ownership that would block releasing the object. A typical example of such things are observers that want to know of any changes to the underlying object but don't want to keep it around if nobody else is using that object.