C++ memory lock() Function
Example
Get the value that a weak_ptr watches:
shared_ptr<int> owner = make_shared<int>(5);
weak_ptr<int> watcher = owner;
shared_ptr<int> temp = watcher.lock();
if (temp) {
cout << *temp;
}
Definition and Usage
The lock() function returns a shared_ptr to the memory that a weak_ptr watches. While you hold this shared_ptr, the memory cannot be freed.
If the memory is already freed, lock() returns an empty shared_ptr. That is why the example checks if (temp) before it uses the value.
The lock function is defined in the <memory> header file.
Syntax
weakPtr.lock();
Only a weak_ptr has this function.
Parameter Values
None.
Technical Details
| Returns: | A shared_ptr to the memory, or an empty shared_ptr if the memory is already freed. |
|---|
Related Pages
Read more about smart pointers in our Smart Pointers Tutorial.