m02-resource

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Resource Management

资源管理

Layer 1: Language Mechanics
第一层:语言机制

Core Question

核心问题

What ownership pattern does this resource need?
Before choosing a smart pointer, understand:
  • Is ownership single or shared?
  • Is access single-threaded or multi-threaded?
  • Are there potential cycles?

该资源需要何种所有权模式?
在选择智能指针之前,请明确:
  • 所有权是独占还是共享?
  • 访问是单线程还是多线程?
  • 是否存在潜在的引用循环?

Error → Design Question

错误 → 设计问题

ErrorDon't Just SayAsk Instead
"Need heap allocation""Use Box"Why can't this be on stack?
Rc memory leak"Use Weak"Is the cycle necessary in design?
RefCell panic"Use try_borrow"Is runtime check the right approach?
Arc overhead complaint"Accept it"Is multi-thread access actually needed?

错误不要只说而应询问
"需要堆分配""使用Box"为什么不能放在栈上?
Rc内存泄漏"使用Weak"设计中是否真的需要这个循环?
RefCell恐慌"使用try_borrow"运行时检查是正确的方案吗?
Arc开销过大"接受它"真的需要多线程访问吗?

Thinking Prompt

思考提示

Before choosing a smart pointer:
  1. What's the ownership model?
    • Single owner → Box or owned value
    • Shared ownership → Rc/Arc
    • Weak reference → Weak
  2. What's the thread context?
    • Single-thread → Rc, Cell, RefCell
    • Multi-thread → Arc, Mutex, RwLock
  3. Are there cycles?
    • Yes → One direction must be Weak
    • No → Regular Rc/Arc is fine

在选择智能指针之前:
  1. 所有权模型是什么?
    • 独占所有权 → Box 或自有值
    • 共享所有权 → Rc/Arc
    • 弱引用 → Weak
  2. 线程上下文是什么?
    • 单线程 → Rc、Cell、RefCell
    • 多线程 → Arc、Mutex、RwLock
  3. 是否存在引用循环?
    • 是 → 其中一个方向必须使用Weak
    • 否 → 常规Rc/Arc即可

Trace Up ↑

向上追溯 ↑

When pointer choice is unclear, trace to design:
"Should I use Arc or Rc?"
    ↑ Ask: Is this data shared across threads?
    ↑ Check: m07-concurrency (thread model)
    ↑ Check: domain-* (performance constraints)
SituationTrace ToQuestion
Rc vs Arc confusionm07-concurrencyWhat's the concurrency model?
RefCell panicsm03-mutabilityIs interior mutability right here?
Memory leaksm12-lifecycleWhere should cleanup happen?

当指针选择不明确时,追溯到设计层面:
"应该使用Arc还是Rc?"
    ↑ 询问:该数据是否跨线程共享?
    ↑ 查看:m07-concurrency(线程模型)
    ↑ 查看:domain-*(性能约束)
场景追溯至问题
混淆Rc与Arcm07-concurrency并发模型是什么?
RefCell恐慌m03-mutability这里使用内部可变性是否正确?
内存泄漏m12-lifecycle清理操作应该在何处执行?

Trace Down ↓

向下落地 ↓

From design to implementation:
"Need single-owner heap data"
    ↓ Use: Box<T>

"Need shared immutable data (single-thread)"
    ↓ Use: Rc<T>

"Need shared immutable data (multi-thread)"
    ↓ Use: Arc<T>

"Need to break reference cycle"
    ↓ Use: Weak<T>

"Need shared mutable data"
    ↓ Single-thread: Rc<RefCell<T>>
    ↓ Multi-thread: Arc<Mutex<T>> or Arc<RwLock<T>>

从设计到实现:
"需要独占所有权的堆数据"
    ↓ 使用:Box<T>

"需要共享不可变数据(单线程)"
    ↓ 使用:Rc<T>

"需要共享不可变数据(多线程)"
    ↓ 使用:Arc<T>

"需要打破引用循环"
    ↓ 使用:Weak<T>

"需要共享可变数据"
    ↓ 单线程:Rc<RefCell<T>>
    ↓ 多线程:Arc<Mutex<T>> 或 Arc<RwLock<T>>

Quick Reference

快速参考

TypeOwnershipThread-SafeUse When
Box<T>
SingleYesHeap allocation, recursive types
Rc<T>
SharedNoSingle-thread shared ownership
Arc<T>
SharedYesMulti-thread shared ownership
Weak<T>
Weak refSame as Rc/ArcBreak reference cycles
Cell<T>
SingleNoInterior mutability (Copy types)
RefCell<T>
SingleNoInterior mutability (runtime check)
类型所有权线程安全适用场景
Box<T>
独占堆分配、递归类型
Rc<T>
共享单线程共享所有权
Arc<T>
共享多线程共享所有权
Weak<T>
弱引用与Rc/Arc一致打破引用循环
Cell<T>
独占内部可变性(Copy类型)
RefCell<T>
独占内部可变性(运行时检查)

Decision Flowchart

决策流程图

Need heap allocation?
├─ Yes → Single owner?
│        ├─ Yes → Box<T>
│        └─ No → Multi-thread?
│                ├─ Yes → Arc<T>
│                └─ No → Rc<T>
└─ No → Stack allocation (default)

Have reference cycles?
├─ Yes → Use Weak for one direction
└─ No → Regular Rc/Arc

Need interior mutability?
├─ Yes → Thread-safe needed?
│        ├─ Yes → Mutex<T> or RwLock<T>
│        └─ No → T: Copy? → Cell<T> : RefCell<T>
└─ No → Use &mut T

需要堆分配?
├─ 是 → 独占所有权?
│        ├─ 是 → Box<T>
│        └─ 否 → 多线程?
│                ├─ 是 → Arc<T>
│                └─ 否 → Rc<T>
└─ 否 → 栈分配(默认)

存在引用循环?
├─ 是 → 其中一个方向使用Weak
└─ 否 → 常规Rc/Arc

需要内部可变性?
├─ 是 → 需要线程安全?
│        ├─ 是 → Mutex<T> 或 RwLock<T>
│        └─ 否 → T: Copy? → Cell<T> : RefCell<T>
└─ 否 → 使用 &mut T

Common Errors

常见错误

ProblemCauseFix
Rc cycle leakMutual strong refsUse Weak for one direction
RefCell panicBorrow conflict at runtimeUse try_borrow or restructure
Arc overheadAtomic ops in hot pathConsider Rc if single-threaded
Box unnecessaryData fits on stackRemove Box

问题原因修复方案
Rc循环泄漏相互强引用其中一个方向使用Weak
RefCell恐慌运行时借用冲突使用try_borrow或重构代码
Arc开销过大热点路径中的原子操作如果是单线程场景,考虑使用Rc
不必要的Box数据可放在栈上移除Box

Anti-Patterns

反模式

Anti-PatternWhy BadBetter
Arc everywhereUnnecessary atomic overheadUse Rc for single-thread
RefCell everywhereRuntime panicsDesign clear ownership
Box for small typesUnnecessary allocationStack allocation
Ignore Weak for cyclesMemory leaksDesign parent-child with Weak

反模式危害更佳方案
处处使用Arc不必要的原子操作开销单线程场景使用Rc
处处使用RefCell运行时恐慌风险设计清晰的所有权模型
为小类型使用Box不必要的分配栈分配
忽略Weak解决循环内存泄漏设计父子关系并使用Weak

Related Skills

相关技能

WhenSee
Ownership errorsm01-ownership
Interior mutability detailsm03-mutability
Multi-thread contextm07-concurrency
Resource lifecyclem12-lifecycle
场景参考
所有权错误m01-ownership
内部可变性细节m03-mutability
多线程上下文m07-concurrency
资源生命周期m12-lifecycle