0Pricing
C++ Academy · Lesson

shared_ptr and weak_ptr Shared Ownership

Share ownership with reference counting and break cycles with weak_ptr.

shared_ptr and weak_ptr Shared Ownership is a free C++ Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C++ Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Sharing an Object

Sometimes multiple parts of the program need to keep an object alive. std::shared_ptr<T> handles shared ownership with reference counting.

Creating a shared_ptr

Use std::make_shared — it allocates the control block and object in one allocation.

#include <memory>
auto s = std::make_shared<Widget>(42);
std::cout << s.use_count();   // 1

Copying Shares Ownership

Copying a shared_ptr increments the ref count. Destroying or reassigning decrements it. When count reaches 0, the object is deleted.

auto a = std::make_shared<Widget>();
auto b = a;                  // ref count is now 2
std::cout << a.use_count();  // 2

How It Works Under the Hood

A shared_ptr holds two pointers: one to the object, one to a control block containing the ref count(s). The control block is heap allocated.

Atomic Ref Count

The ref count uses atomic operations so shared_ptrs can be copied across threads safely. However, the pointed-to object itself is not automatically thread safe.

Resetting and Reassigning

Assigning a new value decrements the old ref count and increments the new. reset() sets the shared_ptr to empty.

shared_ptr from Raw Pointer (Avoid)

Do not construct two shared_ptrs from the same raw pointer — both would have their own control blocks. Always use make_shared.

// BUG
Widget* raw = new Widget();
std::shared_ptr<Widget> a(raw);
std::shared_ptr<Widget> b(raw);   // disaster: two control blocks

The Cycle Problem

Two shared_ptrs that reference each other form a cycle — neither s ref count reaches zero, and neither is freed. Memory leak.

struct Node {
    std::shared_ptr<Node> next;
};
auto a = std::make_shared<Node>();
auto b = std::make_shared<Node>();
a->next = b;
b->next = a;     // cycle — never freed

Breaking Cycles with weak_ptr

std::weak_ptr<T> observes a shared_ptr without participating in the ref count. Use one side of a relationship as weak to break the cycle.

struct Node {
    std::shared_ptr<Node> next;
    std::weak_ptr<Node>  prev;     // weak — does not own
};

Using weak_ptr

You cannot dereference a weak_ptr directly. Call lock() to get a shared_ptr (or empty if the object died).

std::weak_ptr<Widget> w = sharedPtr;
if (auto p = w.lock()) {
    p->use();   // safe — we have a shared_ptr now
} else {
    std::cout << "object expired";
}

Cost vs unique_ptr

shared_ptr is larger (two pointers + control block) and slower (atomic ref count). Use it only when ownership truly needs to be shared.

Quick Check

What is the typical use case for std::weak_ptr?

Recap

shared_ptr tracks ownership with an atomic ref count. Use make_shared, beware cycles, and break them with weak_ptr. Prefer unique_ptr when sharing is not needed.

Frequently asked questions

Is the “shared_ptr and weak_ptr Shared Ownership” lesson free?

Yes — the full text of “shared_ptr and weak_ptr Shared Ownership” is free to read here on the web, and the C++ Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C++ Academy course, upgrade to CoddyKit PRO.

What will I learn in “shared_ptr and weak_ptr Shared Ownership”?

Share ownership with reference counting and break cycles with weak_ptr. You practise C++ Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start C++ Academy?

No prior experience is required. C++ Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “shared_ptr and weak_ptr Shared Ownership” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this C++ Academy lesson?

Yes. Every C++ Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Why Smart Pointers Replace Raw new delete
  2. unique_ptr Exclusive Ownership
  3. shared_ptr and weak_ptr Shared Ownership
  4. Custom Deleters and Make Functions
← Back to C++ Academy