Reference counting with std::shared_ptr<T>

Having completely solved the problem of memory leaks, we now tackle the problem of use-after-free bugs. The essential problem to be solved here is unclear ownership--or rather shared ownership--of a given resource or chunk of memory. This chunk of memory might have several people looking at it at different times, maybe from different data structures or from different threads, and we want to make sure that all these stakeholders are involved in the decision about when to free it. The ownership of the underlying chunk of memory should be shared.

For this, the standard has provided std::shared_ptr<T>. Its interface appears very similar to std::unique_ptr<T>; all of the differences are hidden under the ...

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

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.