Effective modern C ++ (p. 136) uses the following example for motivation std::weak_ptr. A cache is defined as an unordered map with weak pointers to objects as values. Whenever clients of this cache request an object (by key), the corresponding weak pointer is scanned and called on it lock(). If the result is std::shared_ptrnot null, it returns. Otherwise, the object is reloaded from the external database, entered into the cache, and std::shared_ptrreturned.
Now the question is: you might think that it would be possible to implement this without std::weak_ptr, but instead, keep reliable common pointers as cache values. If the use_count()strong pointer is one, this means that all client pointers have been destroyed. Is the whole point of this example that using std::weak_ptrallows us to save memory by actually deleting objects?
source
share