Bloomberg LP Interview Question
Software Engineer / DevelopersCountry: United States
Interview Type: In-Person
Another case where weak_ptr helps is: To avoid dangling pointer.
A shared_ptr can be used to hold the memory. weak_ptr could be supplied to the user. When shared_ptr resets to a new memory, a weak_ptr gets invalidated thus avoiding dangling pointer. To realize this, weak_ptr has method "lock" which returns shared_ptr which it points to. When shared_ptr is reset, it returns default constructed shared_ptr.
We need to use weak_ptr to avoid cycles in data structures. weak_ptr points to a resource which is managed by one or more shared_ptr. As the weak_ptr does not effects the resource reference count(weak_ptr holds weak or non-owning reference) so when the last shared_ptr object that manages that resource is destroyed the resource will be freed even if the resource is pointed by a weak_ptr. For the cycle problem think about a circular link list. Where, if every node holds the shared_ptr which owns the next node will never be freed because none of the reference count can be zero. To avoid this problem, if the last node hold weak_ptr object of the first node, then the first node can be destroyed even it is pointed from the last node.
- Palash April 07, 2012