C++ memory weak_ptr Class
Example
A weak_ptr does not change the number of owners:
shared_ptr<int> owner = make_shared<int>(5);
weak_ptr<int> watcher = owner;
cout << owner.use_count();
Definition and Usage
A weak_ptr points to memory that is owned by a shared_ptr, but it is not an owner itself. In the example, the count is still 1, because watcher does not count as an owner.
The memory can be freed while the weak_ptr still exists. So before you use the value, call lock() to get a shared_ptr to it.
The weak_ptr class is defined in the <memory> header file.
Syntax
weak_ptr<type> name = sharedPtr;
Parameter Values
| Parameter | Description |
|---|---|
| sharedPtr | Required. The shared_ptr that owns the memory. |
Technical Details
| Returns: | A weak_ptr object that watches the memory. |
|---|
Related Pages
Read more about smart pointers in our Smart Pointers Tutorial.