rust - Rust 的内存管理与编译时垃圾收集有何不同?

标签 rust garbage-collection

我读到 Rust 的编译器在编译时“插入”内存管理代码,这听起来有点像“编译时垃圾收集”。

这两种想法有什么区别?

我见过What does Rust have instead of a garbage collector?但这是关于运行时垃圾收集,而不是编译时。

最佳答案

编译时垃圾收集通常定义如下:

A complementary form of automatic memory management is compile-time memory management (CTGC), where the decisions for memory management are taken at compile-time instead of at run-time. The compiler determines the life-time of the variables that are created during the execution of the program, and thus also the memory that will be associated with these variables. Whenever the compiler can guarantee that a variable, or more precisely, parts of the memory resources that this variable points to at run-time, will never ever be accessed beyond a certain program instruction, then the compiler can add instructions to deallocate these resources at that particular instruction without compromising the correctness of the resulting code.

(来自 Compile-Time Garbage Collection for the Declarative Language Mercury by Nancy Mazur )

Rust 通过使用所有权和借用检查的概念来处理内存。所有权和移动语义描述了哪个变量拥有一个值。借用描述了允许哪些引用访问某个值。这两个概念允许编译器在该值不再可访问时“删除”该值,从而导致程序从Drop调用dtop方法。特质)。

但是,编译器本身根本不处理动态分配的内存。它仅处理删除检查(确定何时调用 drop)并插入 .drop() 调用。 drop 实现负责确定此时发生的情况,是否释放一些动态内存(例如 Boxdrop 所做的),或做其他事情。因此,编译器永远不会真正强制执行垃圾收集,并且不会强制释放未使用的内存。因此,我们不能声称 Rust 实现了编译时垃圾收集,即使 Rust 的功能很容易让人想起它。

关于rust - Rust 的内存管理与编译时垃圾收集有何不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66629053/

相关文章:

string - 类似 str 的迭代器

rust - 将引用作为参数更正 Into<Foo> 的生命周期

memory-leaks - Go:内存使用过多,内存泄漏

javascript - 关于垃圾回收的 Null 和 delete()

rust - 以索引为键的 serde_json 展平对象

syntax - 为什么以及何时应该在 block 的末尾使用逗号?

Java 8 元空间 : OutOfMemoryError: Dealing with reflection Inflation

android - 有人可以解释 RemoteViews GC 行为吗?

rust - "expected identifier"创建宏时同时定义可变变量

java - PrintGCApplicationStoppedTime 报告的 "stop the world"时间真的准确吗?