Search⌘ K

Shared Pointers

Explore the use of std::shared_ptr in C++ to share ownership of resources efficiently. Understand how reference counting works to automate memory management and prevent leaks. Learn key methods and practices including std::make_shared and std::enable_shared_from_this for safer and faster smart pointer usage.

Introduction

std::shared_ptr shares ownership of the resource. They have two handles: one for the resource, and one for the reference counter. By copying an 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 longer an 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 ...