Rust 内存管理:所有权 vs. 引用计数
Rust Memory Management: Ownership vs. Reference Counting

原始链接: https://slicker.me/rust/ownership_and_borrowing_vs_reference_counting.html

Rust 通过其独特的 ownership 系统保证内存安全,而无需垃圾回收器。每个值都有一个单独的所有者,当 ownership 结束时,内存会被自动释放——确保没有悬垂指针或双重释放。然而,有时数据*需要*被共享。 这时就出现了引用计数,通过 `Rc` 和 `Arc`。这些类型不会消除 ownership,而是使用运行时计数器跟踪一个值有多少个所有者。只有当计数器达到零时,该值才会被释放。 `Rc` 是单线程的,提供较低的开销,而 `Arc` (Atomic Reference Counting) 是线程安全的。重要的是,引用计数不是 Rust ownership 系统的替代品;它是在需要共享 ownership 的特定场景中的补充工具,在安全性和性能之间提供权衡。在 `Rc` 和 `Arc` 之间进行选择取决于应用程序的线程需求。

Hacker News 新闻 | 过去 | 评论 | 提问 | 展示 | 招聘 | 提交 登录 Rust 内存管理:所有权 vs. 引用计数 (slicker.me) 5 分,vinhnx 发表于 2 小时前 | 隐藏 | 过去 | 收藏 | 1 条评论 帮助 jonathanstrange 发表于 10 分钟前 | 上一个 [–] 感谢,但我还是会使用带有垃圾回收器的现代语言,把时间花在实际问题上,而不是自找麻烦。回复 考虑申请 YC 2026 夏季班!申请截止至 5 月 4 日 指南 | 常见问题 | 列表 | API | 安全 | 法律 | 申请 YC | 联系 搜索:
相关文章

原文

Rust's signature achievement is memory safety without a garbage collector. It accomplishes this through a disciplined ownership system — but that system deliberately has an escape hatch: reference counting.

Every value in a Rust program has a single owner at any given time. When that owner goes out of scope, the value is dropped — memory freed, deterministically, at a known point in execution. No GC pause, no dangling pointer, no double-free. The compiler enforces all of this statically.

But some data genuinely needs to be shared: a node in a graph owned by multiple edges, a configuration object threaded through many subsystems, a callback holding a reference into surrounding state. Enter reference countingRc<T> and Arc<T> — which shift ownership logic from compile time into a small runtime counter.

These are not competing features. They are complementary tools with distinct trade-offs. This article unpacks both — semantics, performance, ergonomics, and the decisive question: which should you reach for?

联系我们 contact @ memedata.com