On this page
  1. std::shared_ptr
  2. Overview
  3. Notes & Pitfalls
  4. Example

std::shared_ptr

Prev: std::make_unique | Up: memory | Next: std::weak_ptr
Rel: std::unique_ptr, std::weak_ptr
Ref: cppreference — std::shared_ptr
Tags: #public #prog #cpp #stdlib #memory #tier/standard


Overview

std::shared_ptr<T> (<memory>) provides reference-counted shared ownership across multiple owners. The managed object is destroyed when the last shared_ptr owning it is destroyed or reset. Reference count increments/decrements are thread-safe (atomic), though the pointee itself still needs synchronization if mutated concurrently.

Notes & Pitfalls

Example

#include <cassert>
#include <memory>

int main() {
    auto a = std::make_shared<int>(42);
    auto b = a;
    assert(a.use_count() == 2 && *b == 42);
}

Linked from

Related notes