Smart Pointers: Shared Pointers

Next, we will go over shared pointers, which follow the principle of keeping a reference count to maintaining the count of its copies. The lesson below elaborates further.

Introduction

std::shared_ptr shares the ownership of the resource. They have two handles: one for the resource and one for the reference counter. By copying a std::shared_ptr, the reference count is increased by one. It is decreased by one if the std::shared_ptr goes out of scope. If the reference counter becomes the value 0, the C++ runtime automatically releases the resource, since there is no std::shared_ptr referencing the resource. The release of the resource occurs exactly when the last std::shared_ptr goes out of scope. The C++ runtime guarantees that the call of the reference counter is an atomic operation. Due to this management, std::shared_ptr consumes more time and memory than a raw pointer or std::unique_ptr.

Take a look at the image below to better visualize the concept.

Get hands-on with 1000+ tech skills courses.