std::weak_ptr
- C++ course
- Intermediate
- Lesson 84/116
- 5 min
Learn to break circular references with std::weak_ptr.
std::weak_ptr
std::weak_ptr is a weak (non-owning) observer of a shared_ptr. It can observe an object without incrementing the reference count. You create a weak_ptr from a shared_ptr: std::weak_ptr<int> wp = sp;.
The purpose of weak_ptr is to break circular references. If two objects hold each other via shared_ptr neither is ever deleted (the count never reaches 0). If one side uses weak_ptr the cycle is broken. A weak_ptr cannot be dereferenced directly; you first call lock() to get a shared_ptr. If the object still lives you get a valid pointer, otherwise an empty one.
Access with lock()
A weak_ptr cannot be dereferenced directly with *. Instead the lock() method returns a shared_ptr: auto p = wp.lock();. If the object still lives p is valid, otherwise empty.
Example: if (auto p = wp.lock()) { std::cout << *p; }. Here if lock() succeeds p is a valid shared_ptr and *p accesses the value. If it fails p is empty and the if condition is false. This is the safe way to use weak_ptr; you never access without controlling the object's lifetime.
Practice Safe access with weak_ptr
A shared_ptr named sp is already defined with std::make_shared<int>(99). Create a weak observer with std::weak_ptr<int> wp = sp;. Access safely with if (auto p = wp.lock()) and print *p with std::cout.
Starter code
#include <iostream>
#include <memory>
int main() {
std::shared_ptr<int> sp = std::make_shared<int>(99);
// Create a weak_ptr from sp, access via lock, print
return 0;
}Sample solution
#include <iostream>
#include <memory>
int main() {
std::shared_ptr<int> sp = std::make_shared<int>(99);
std::weak_ptr<int> wp = sp;
if (auto p = wp.lock()) {
std::cout << *p;
}
return 0;
}Expected output
99
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match each feature to its meaning
| Term | Meaning |
|---|---|
std::weak_ptr |
Weak observer |
wp.lock() |
Get shared_ptr |
Circular reference |
Leak source |
Reference count |
Not incremented |
2 Declare a weak_ptr
std::____<int> wp = sp;
std::weak_ptr<int> wp = sp;
Explanation: weak_ptr provides a weak observer.
3 What problem does weak_ptr prevent?
// two objects hold each other via shared_ptr
// if one uses weak_ptr- Memory overflow
- Circular reference leak Correct answer
- Null pointer
- Compile error
Explanation: weak_ptr breaks circular references and prevents leaks.