0Pricing
C++ Academy · Lesson

shared_ptr and weak_ptr Shared Ownership

Share ownership with reference counting and break cycles with weak_ptr.

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

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