Curriculumstd::weak_ptr

std::weak_ptr

A <code>std::weak_ptr</code> is a companion to <code>shared_ptr</code>. It allows you to 'observe' or look at the memory owned by a shared_ptr, but it <strong>does not increase the reference count</strong>. It does not own the memory.

01Observing without Owning

When you create a weak_ptr from a shared_ptr, notice that the use_count() does not go up!

It is just watching the memory.
main.cpp
Loading...
Terminal
Waiting for execution...
Visualizer

Click Run to see memory state

02Safe Access with .lock()

To use the data, you must call .lock(). This checks if the memory is still alive.

If it is, it returns a temporary shared_ptr you can use. If the memory was deleted, it returns a nullptr.
main.cpp
Loading...
Terminal
Waiting for execution...

03Fixing Circular References

Let's fix the memory leak from the previous lesson!

If Object A owns Object B (shared), but Object B only observes Object A (weak), the cycle is broken. The reference count will successfully hit 0 and both destructors will run!
main.cpp
Loading...
Terminal
Waiting for execution...
← Back to Curriculum