From 37401ada8b98a1ec47f288afa6cb01337ca2e4b3 Mon Sep 17 00:00:00 2001 From: Dw9 <36155473+Dw9@users.noreply.github.com> Date: Sat, 20 Nov 2021 23:01:25 +0800 Subject: [PATCH] book: add std::weak_ptr::lock (#216) --- book/en-us/05-pointers.md | 3 ++- book/zh-cn/05-pointers.md | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/book/en-us/05-pointers.md b/book/en-us/05-pointers.md index acd8ebe..2e24880 100644 --- a/book/en-us/05-pointers.md +++ b/book/en-us/05-pointers.md @@ -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 diff --git a/book/zh-cn/05-pointers.md b/book/zh-cn/05-pointers.md index 6688bd1..bdfaf59 100644 --- a/book/zh-cn/05-pointers.md +++ b/book/zh-cn/05-pointers.md @@ -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`。 ## 总结