知识卡片
弱引用升级检查存活
Rc::downgrade(&owner) 建立弱引用,保留查找目标的能力而不延长内部值寿命。weak.upgrade() 在值仍存在时产生新的强句柄,值已析构或引用为空时返回 None。因此调用者不能假定链接总能找到目标。
相关卡片 [[强引用闭环无法归零]]
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- 智能指针 Preventing Reference Cycles Using Weak<T> · 查看原书依据
Because the value that Weak<T> references might have been dropped, to do anything with the value that a Weak<T> is pointing to you must make sure the value still exists. Do this by calling the upgrade method on a Weak<T> instance, which will return an Option<Rc<T>>.
参考来源
- 位置:《The Rust Programming Language(第2版)》第15章 智能指针(来源项目 a19c7933-4eda-4176-aebd-30fe7e1ad292,`extracted/The Rust Programming Language(第2版)/_epub-src/c15.xhtml`,块 0319)
- 结论依据:原文用 `Option<Rc<T>>` 的两个变体说明访问需要验证目标寿命。
- 原始内容:Because the value that Weak<T> references might have been dropped, to do anything with the value that a Weak<T> is pointing to you must make sure the value still exists. Do this by calling the upgrade method on a Weak<T> instance, which will return an Option<Rc<T>>.