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

How does Rust's memory management differ from compile-time garbage collection?

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

这两个想法有什么区别?

我看过 但那是关于运行时垃圾收集,而不是编译时。

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

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 的东西很像它。