dimanche 19 juillet 2015

Did I understand correctly the point of Scott Meyers' example of std::weak_ptr?

Effective Modern C++ (page 136) uses the following example to motivate 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 looked up and lock() is invoked on it. If the resulting std::shared_ptr is not null, it is returned. Otherwise, the object is re-loaded from an external database, entered into the cache and std::shared_ptr to it is returned.

Now the question: one might think that it would be possible to implement this without std::weak_ptr, but to store strong shared pointers as cache values instead. If use_count() of a strong pointer is equal to one, that means that all the client's pointers have been destroyed. Is the whole point of this example that using std::weak_ptr allows us to save memory by actually deleting the objects?

Aucun commentaire:

Enregistrer un commentaire