7

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 3

11

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.

Sign up to request clarification or add additional context in comments.

8 Comments

Why is this necessary?
@Tracer: Why is the weak_ptr necessary? Or why is a counter for weak_ptrs necessary?
@Tracer Suppose it didn't work like that. How would a weak_ptr then know whether the pointed-to object has been deleted yet?
@hvd I thought strong reference counter is used to know if managed object still exists.
@Tracer It is, but the reference count block itself needs to keep track of both the weak and strong reference counts. It only gets destroyed when both reach zero.
|
3

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

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.