Skip to content
Tutorials Center
My learning

Topics

C++ Reference ยท Memory and Utilities

C++ std::shared_ptr class template

Reference for C++ std::shared_ptr: shared ownership with reference counting, copy and move, use_count, reset, aliasing constructor, comparisons and thread safety.

std::shared_ptr<T>, declared in <memory>, is a smart pointer that shares ownership of one object with other shared_ptr instances. A reference count in a hidden control block records how many owners exist. When the last owner is destroyed or reset, the object is deleted.

Use it when no single owner is obvious, for example a cache entry that several callers keep alive. If one owner is enough, std::unique_ptr is cheaper and simpler.

C++
auto p = std::make_shared<std::string>("hello");
auto q = p;                  // two owners, one string
std::println("{}", p.use_count());   // 2

Try it

C++ Owners, copies and moves

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

C++ Aliasing constructor and comparisons

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Syntax

C++
template<class T> class shared_ptr;

shared_ptr();                         // empty
shared_ptr(nullptr_t);                // empty
explicit shared_ptr(T* p);            // takes ownership (delete p later)
shared_ptr(T* p, Deleter d);          // custom deleter
shared_ptr(const shared_ptr& r);      // copy: shares ownership
shared_ptr(shared_ptr&& r) noexcept;  // move: steals ownership
template<class Y> shared_ptr(const shared_ptr<Y>& r, T* ptr) noexcept;  // aliasing
Member Description
get() Returns the stored raw pointer without changing ownership.
operator*, operator-> Access the object. Undefined behavior if the pointer is empty.
use_count() Number of shared_ptr owners (0 for an empty pointer). Only approximate in multithreaded code.
reset(), reset(p) Release this owner's share; optionally take ownership of p.
swap(other) Exchanges pointers and control blocks.
operator bool true if the stored pointer is not null.
owner_before(other) Ordering based on the control block, used for map keys.

Returns: use_count() returns long. Errors: the constructor from a raw pointer may throw std::bad_alloc when allocating the control block (the pointer is then deleted for you). Dereferencing an empty shared_ptr is undefined behavior.

Usage notes

  • Prefer std::make_shared<T>(args...): one allocation for object and control block, and no chance of a leak between new and construction. See make_unique and make_shared.
  • Never create two independent shared_ptrs from the same raw pointer. Each gets its own control block and both will delete the object, which is a double free. Copy the first shared_ptr instead.
  • The reference count updates are atomic, so copying a shared_ptr from several threads is safe. The pointed-to object is not protected: concurrent writes still need a mutex.
  • Assigning to the same shared_ptr object from two threads at once is a data race. Use std::atomic<std::shared_ptr<T>> (C++20) for that.
  • Copying costs an atomic increment. Pass by const shared_ptr& or by raw reference when the callee does not need to share ownership.
  • shared_ptr<T[]> supports arrays since C++17 (std::make_shared<int[]>(5) since C++20) and calls delete[] correctly.
  • == and < compare stored pointers, not the pointed-to values, as the second example shows.
  • A cycle (A owns B owns A) is never freed. Break it with weak_ptr.
  • Converting to a base class works implicitly (shared_ptr<Derived> to shared_ptr<Base>) and the right destructor still runs, even without a virtual destructor, because the deleter remembers the original type. Use static_pointer_cast, dynamic_pointer_cast and const_pointer_cast to go the other way.