知识卡片
反向导航不必承担拥有责任
树向下拥有子节点时,向上的父链接可用Weak,避免父子互相强持有而无法释放。调用前upgrade取得临时强引用,必须处理父对象已消失。示例expect只是选择panic策略;树模型若允许孤立节点,就不能把父一定存在当成天然保证。
结构图:
classDiagram
class Tree {
id: TreeId
branches: Vec~Rc_RefCell_Branch~
}
class Branch {
id: BranchId
leaves: Vec~Rc_RefCell_Leaf~
owner: Option~Weak_RefCell_Tree~
+add_leaf(branch: Rc_RefCell_Branch, leaf: Leaf)
+location(&self) String
}
class Leaf {
id: LeafId
owner: Option~Weak_RefCell_Branch~
}
Tree --> Branch : Rc共享拥有
Branch --> Leaf : Rc共享拥有
Branch ..> Tree : Weak非拥有链接
Leaf ..> Branch : Weak非拥有链接
图中下划线简写嵌套泛型,如Rc_RefCell_Branch实际为Rc>。实线表示强引用拥有,虚线表示可失效导航;不是继承关系。
这张卡片看不懂?
这张卡片的反馈已满 10 条,暂时无法继续提交。
已有反馈 · 0 / 10 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- Chapter 3. Concepts Smart pointers · 查看原书依据
Weak reference doesn’t increment the main refcount and so has to explicitly check whether the underlying item has gone away: impl Branch { fn add_leaf(branch: Rc<RefCell<Branch>>, mut leaf: Leaf) { leaf.owner = Some(Rc::downgrade(&branch)); branch.borrow_mut().leaves.push(Rc::new(RefCell::new(leaf))); } fn location(&self) -> String { match &self.owner { None
参考来源
- 位置:《Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)》第3章《Smart pointers》(spine7;extracted/Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)/_epub-src/OEBPS/ch03.html;u095-ch03-021)。
- 结论依据:原文在“Weak reference”附近的定义、例子或代码支撑本卡核心说明:树向下拥有子节点时,向上的父链接可用Weak,避免父子互相强持有而无法释放。边界按已读前提解释;示例未执行。
- 原始内容:Weak reference doesn’t increment the main refcount and so has to explicitly check whether the underlying item has gone away: impl Branch { fn add_leaf(branch: Rc<RefCell<Branch>>, mut leaf: Leaf) { leaf.owner = Some(Rc::downgrade(&branch)); branch.borrow_mut().leaves.push(Rc::new(RefCell::new(leaf))); } fn location(&self) -> String { match &self.owner { None