mirror of
https://github.com/changkun/modern-cpp-tutorial.git
synced 2025-12-16 20:27:08 +03:00
book: add std::weak_ptr<T>::lock (#216)
This commit is contained in:
@@ -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
|
||||
|
||||
|
||||
@@ -173,7 +173,7 @@ int main() {
|
||||
|
||||
在上图中,最后一步只剩下 B,而 B 并没有任何智能指针引用它,因此这块内存资源也会被释放。
|
||||
|
||||
`std::weak_ptr` 没有 `*` 运算符和 `->` 运算符,所以不能够对资源进行操作,它的唯一作用就是用于检查 `std::shared_ptr` 是否存在,其 `expired()` 方法能在资源未被释放时,会返回 `false`,否则返回 `true`。
|
||||
`std::weak_ptr` 没有 `*` 运算符和 `->` 运算符,所以不能够对资源进行操作,它可以用于检查 `std::shared_ptr` 是否存在,其 `expired()` 方法能在资源未被释放时,会返回 `false`,否则返回 `true`;除此之外,它也可以用于获取指向原始对象的 `std::shared_ptr` 指针,其 `lock()` 方法在原始对象未被释放时,返回一个指向原始对象的 `std::shared_ptr` 指针,进而访问原始对象的资源,否则返回`nullptr`。
|
||||
|
||||
## 总结
|
||||
|
||||
|
||||
Reference in New Issue
Block a user