Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Smart Pointers: Beyond Single Ownership
智能指针:超越单一所有权

What you’ll learn: When Box, Rc, Arc, RefCell, and Mutex are needed, and how they compare to Java’s always-reference-based object model.
本章将学习: 什么时候该用 BoxRcArcRefCellMutex,以及它们和 Java 那种“对象默认全靠引用”模型有什么区别。

Difficulty: 🔴 Advanced
难度: 🔴 高级

Java developers are used to object references everywhere. Rust starts from direct ownership and only adds pointer-like wrappers when they are actually needed.
Java 开发者习惯了对象到处都是引用。Rust 则是先从直接所有权开始,只有真的需要时才引入带指针味道的包装类型。

Common Smart Pointers
常见智能指针

TypeTypical use
Box<T>heap allocation with single ownership
单一所有权下的堆分配
Rc<T>shared ownership in single-threaded code
单线程共享所有权
Arc<T>shared ownership across threads
跨线程共享所有权
RefCell<T>checked interior mutability in single-threaded code
单线程内部可变性
Mutex<T>synchronized shared mutable access
同步共享可变访问

The Key Difference from Java
和 Java 的关键差异

In Java, shared references are the default. In Rust, shared ownership is a deliberate choice with a specific type.
在 Java 里,共享引用是默认状态;在 Rust 里,共享所有权必须通过专门类型显式表达。

Guidance
使用建议

  • use plain values and references first
    优先从普通值和引用开始。
  • add Box when recursive or heap-allocated layout is needed
    递归结构或需要稳定堆布局时,再加 Box
  • add Rc or Arc only when multiple owners are truly required
    只有真的存在多个 owner 时,再上 RcArc
  • pair Arc with Mutex only when shared mutable state is unavoidable
    只有共享可变状态躲不过去时,才把 ArcMutex 配一起。

These types are powerful, but they are also signals that the ownership model has become more complex.
这些类型很好用,但它们同时也是信号:代码里的所有权关系已经开始变复杂了。