Boost logo

Boost Users :

From: bjorn.karlsson_at_[hidden]
Date: 2003-04-15 03:20:11


> From: Edward Diener [mailto:eddielee_at_[hidden]]
>
> I don't understand what the practical use of Boost weak_ptr<>
> is ? Anyone
> like to clue me in ? I understand that Boost weak_ptr<>
> creates an internal
> reference to a Boost shared_ptr<> but I don't understand what that is
> supposed to accomplish.

A weak_ptr is an observer of the pointee, i.e it doesn't take part of the
lifetime management of the resource. One use for it is to break cyclic
dependencies; another is to avoid dangling pointers. When a shared_ptr
deallocates its pointee, it notifies the weak_ptrs. When the weak_ptr is
subsequently used, it knows that the resource is gone (compare this with
storing raw pointers, where there is no way to tell whether the pointer is
still valid or not).

Example:
A Company class has a container that holds elements of type
shared_ptr<Employee>. Now, the Supervisor class needs to know things about
certain Employees, but it cannot/must not control their lifetime (in the
context of the Company class, that is). Rather than asking the Company to
search through each Employee (for example by name) each time Supervisor
needs to access/update some Employee information, it caches information in
weak_ptr<Employee> for efficient access. If an Employee quits (is removed
from the container of shared_ptr<Employee>), the Supervisor class will be
informed of this the next time it tries to access that weak_ptr<Employee>.
At the time of access, a (temporary) shared_ptr is created from a weak_ptr,
to ensure that the pointee isn't deleted in the midst of using it.

Without weak_ptr, the above would be hard(er) to accomplish:

* Asking Company to find an Employee each time it is needed may be too
inefficient.
* Storing shared_ptr<Employee> in the Supervisor class interferes with
lifetime management and can cause inconsistent state.
* Storing a raw pointer to an Employee is extremely dangerous (known as the
dangling Employee problem); there's no way of telling if the pointer is
valid.

Bjorn Karlsson


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net