在重新分配持有该值所有权的变量之后,堆分配的值会发生什么?

时间:2019-08-11 14:59:36

标签: rust

我目前正在学习Rust编程语言,并且在阅读了有关所有权和生存期概念(我发现它是GC的优雅替代品)之后,我找不到以下问题的答案。 就所有权和生存期而言,以下代码按注释所述工作。

fn main() {
    let mut x: u32 = 10; // x is pointing to memory in stack
    println!("before reassignment: x = {}", x); // prints 10
    x = 11; // memory in stack simply has been updated with another value
    println!("after reassignment: x = {}", x); // prints 11
} // x is dropped here

每个人都很高兴,但请想象我们是否有这样的代码:

fn main() {
    let mut x = Box::new([99; 1000]); // x owns a Box, which owns heap allocated array 
    println!("before reassignment: x[0] = {}", x[0]); 
    x = Box::new([100; 1000]); // x has been assigned another Box
    // what happened to previous heap allocated array, has it been
    // dropped behind the scenes, or is that a memory leak?
    println!("after reassignment: x[0] = {}", x[0]);
} // x is dropped here, only the last assigned value gets dropped with it.

堆分配的数组(首先分配的数组)会发生什么,它会一直存在到函数结束,还是会在重新分配时被丢弃? 我仍在学习Rust,所以我对内存管理的理解可能不完整。

该问题与When is the storage reclaimed for a resource that is no longer owned?中提出的问题有所不同,因为这是关于所有者变量仍在范围内,而只是被分配了另一个值的情况。

1 个答案:

答案 0 :(得分:6)

每当您为实现Drop的类型的变量分配新值时,旧值将在分配新值之前被删除。对于拥有Box之类的堆已分配内存的类型,这意味着该内存将在分配时释放。

尽管有可能在安全的Rust代码中泄漏无法访问的内存,但不太可能偶然发生。