std::shared_ptr and std::weak_ptr

We need a smart pointer providing shared ownership. What we need was introduced back in C++11 as std::shared_ptr. It's harder to implement a smart pointer with shared ownership, because you should take care of the correct deallocation of the resource. For example, when the print_name() function in the preceding code block finishes its work, its arguments and local objects will be destroyed. Destroying a smart pointer leads to the proper deallocation of the resource it owns. How would the smart pointer know if that resource is still owned by another smart pointer? One of the popular solutions is keeping the count of references to the resource. The shared_ptr class does the same: it keeps the number of pointers ...

Get Expert C++ 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.