C++20 sections · 1024 units
Open in Course

What is shared_ptr?

Multiple owners

shared_ptr allows multiple pointers to own the same object. It uses reference counting to track how many shared_ptrs point to the resource. When the count drops to zero, it deletes. Copy a shared_ptr and both copies own the object.

Each copy increments the reference count. When any copy is destroyed, the count decrements. Only the last one deletes. Use shared_ptr when ownership is shared, like a cache where multiple parts of code hold references.

For single ownership, unique_ptr is simpler and has less overhead.