Quick A: To keep a pointer on a ressource without owning it.
Recently on SO:
Need of a weak_ptr in C++11
The second half of that statement should be clear: if a pointer is not an owning pointer then the object it is pointing at might be deleted by whatever software is the owner - and then you'd have the standard dangling reference.
So this issue is: you've got objects owned by some piece of software which is letting other software have access to it - but the other software won't share the ownership. So the owner can delete it at any time and the other software needs to know it's pointer is no longer valid.
Maybe an example would help:
You've got some piece of software watching a camera pointing out your window to a bird feeder and it is identifying birds at the feeder, which come and go. Each bird at the feeder has an object created by this software when it arrives at the feeder, and the object is deleted when the bird flies away.
Meanwhile, some other software it taking a census. Every 10 seconds it grabs from the feeder-watching software a collection of the birds at the feeder. Every 100 seconds it emits a report of which birds were at the feeder for the entire 100 seconds.
Because the data for a bird is big the census-taker doesn't copy the data. It merely gets, every 10 seconds, a collection of pointers from the feeder-watcher.
To make it necessary to use weak pointers, let's say the feeder-watcher only provides pointers to birds which have arrived in the last ten seconds, not the ones which have been there. That is, there is no notification that birds have disappeared.
By using weak pointers it can know, at report time, which of the birds are still there, and when they arrived (but not when they left).
(Maybe I'll think of a better example later.)
Add a Comment
Comments are closed.