book: add std::weak_ptr<T>::lock (#216)

This commit is contained in:
Dw9
2021-11-20 23:01:25 +08:00
committed by GitHub
parent c172682723
commit 37401ada8b
2 changed files with 3 additions and 2 deletions

View File

@@ -185,7 +185,8 @@ The solution to this problem is to use the weak reference pointer `std::weak_ptr
In the above figure, only B is left in the last step, and B does not have any smart pointers to reference it, so this memory resource will also be released.
`std::weak_ptr` has no `*` operator and `->` operator, so it can't operate on resources. Its only function is to check if `std::shared_ptr` exists, its `expired()` method can return `false` when the resource is not released, otherwise, it returns `true`.
`std::weak_ptr` has no implemented `*` and `->` operators, therefore it cannot operate on resources. `std::weak_ptr` allows us to check if a `std::shared_ptr` exists or not. The `expired()` method of a `std::weak_ptr` returns `false` when the resource is not released; Otherwise, it returns `true`.
Furthermore, it can also be used for the purpose of obtaining `std::shared_ptr`, which points to the original object. The `lock()` method returns a `std::shared_ptr` to the original object when the resource is not released, or `nullptr` otherwise.
## Conclusion