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
It is just watching the memory.
weak_ptr from a shared_ptr, notice that the use_count() does not go up! It is just watching the memory.
main.cpp
Terminal
Waiting for execution...
Visualizer
Click Run to see memory state
02Safe Access with .lock()
To use the data, you must call
If it is, it returns a temporary
.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
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!
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
Terminal
Waiting for execution...
AI Tutor
weak_ptr is the ultimate solution to the Circular Reference problem we saw in the last lesson. By making one of the connections a weak_ptr, the reference count can successfully hit 0.