Curriculumstd::shared_ptr

std::shared_ptr

While a <code>unique_ptr</code> strictly owns memory by itself, a <code>std::shared_ptr</code> allows multiple pointers to own the exact same heap memory. The memory is only deleted when the <em>last</em> shared pointer pointing to it is destroyed.

01Creating a shared_ptr

We use std::make_shared to create it.

Unlike unique_ptr, we are allowed to copy a shared_ptr. Notice how the use_count() goes up when we make a copy!
main.cpp
Loading...
Terminal
Waiting for execution...
Visualizer

Click Run to see memory state

02Automatic Cleanup (Ref Count 0)

The heap memory is only destroyed when the reference count drops to 0.

Watch what happens when pointers go out of scope in this nested block example.
main.cpp
Loading...
Terminal
Waiting for execution...

03Passing to Functions (By Value)

If you pass a shared_ptr to a function by value, it creates a copy for the function's parameter. This increments the reference count while the function is running!
main.cpp
Loading...
Terminal
Waiting for execution...

04The Danger: Circular References

Because shared_ptr relies on the count hitting 0, it has a fatal flaw: Circular References.

If Player has a shared_ptr to Weapon, and Weapon has a shared_ptr to Player, neither can ever be destroyed. Their counts will be stuck at 1 forever, causing a memory leak!
main.cpp
Loading...
Terminal
Waiting for execution...
← Back to Curriculum