C++ · Advanced level

Advanced level · Module 2: Modern Memory Management · Lesson 3 of 4

shared_ptr and weak_ptr

Use shared ownership only when it is genuinely needed, and break reference cycles with weak_ptr.

In this lesson you will

  • Use std::shared_ptr for shared ownership
  • Break cycles with std::weak_ptr

Key concepts

std::shared_ptrreference countstd::weak_ptrreference cycle

The lesson

std::shared_ptr<T> lets several owners share an object; a reference count tracks the owners, and the object is deleted when the last one disappears. Create it with std::make_shared. Copying a shared_ptr increases the count; this has a small cost, especially across threads.

If two objects hold shared_ptrs to each other, their counts never reach zero and both leak — a reference cycle. Make one direction a std::weak_ptr, which observes without owning; call lock() to get a temporary shared_ptr when you need the object.

Prefer unique_ptr. Use shared_ptr only when ownership is truly shared and lifetimes cannot be expressed more simply; widespread shared_ptr often hides an unclear design.

Step by step

  1. Share one configuration object between two components with shared_ptr.
  2. Print use_count() as owners are added and removed.
  3. Create a parent–child cycle and observe the leak.
  4. Fix it with weak_ptr and lock().
Troubleshooting tree

Which way should this code hold that object?

A quick path to the right choice between a value, a reference, unique_ptr, shared_ptr and weak_ptr.

Can the object simply live as a value (a local, a member or an element of a container)?
  • Yes
    Use a value. It is the simplest, fastest and safest option — no pointers needed.
  • No
    Does this code only use the object while someone else keeps it alive?
    • Yes
      Use a reference (or a raw pointer if 'no object' is possible). It means 'I use this but do not own it'.
    • No
      Will exactly one owner be responsible for deleting it?
      • Yes
        Use std::unique_ptr created with std::make_unique, and std::move it to transfer ownership.
      • No
        Do several owners genuinely share it, with no single clear owner?
        • Yes
          Use std::shared_ptr created with std::make_shared, and std::weak_ptr for back-references to avoid cycles.
        • No
          The ownership is unclear. Redesign so one component owns the object before choosing a pointer type.

Notes

Raw new and delete never appear in the answers: in modern C++ they belong inside low-level library code, not application code.

Practice activity

Model stations and their sensors where sensors refer back to their station without creating a cycle.

Expected result: All objects are destroyed at the end of the program and the sanitizer reports no leaks.

Check your understanding

  1. When is an object owned by shared_ptr deleted?

    Show answer

    When the last shared_ptr owning it is destroyed or reset.

  2. What does weak_ptr do?

    Show answer

    Observes a shared object without owning it, which breaks reference cycles.

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.