Holding nullable handles with weak_ptr

You may have noticed in the previous diagrams, an unexplained data member of the control block marked "weak count". It's time to explain what that is.

Sometimes--it's rare, but sometimes--we have a situation where we're using shared_ptr to manage the ownership of shared objects, and we'd like to keep a pointer to an object without actually expressing ownership of that object. Of course we could use a raw pointer, reference, or observer_ptr<T> to express the idea of "non-owning reference," but the danger then would be that the actual owners of the referenced object could decide to free it, and then when we went to dereference our non-owning pointer, we'd visit a freed object and get undefined behavior. ...

Get Mastering the C++17 STL now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.