简体   繁体   English

没有参考时,Rust中的框类型会自动释放吗?

[英]Are box types in Rust automatically freed when they have no references?

In the following code, does the "box 5i" get properly freed when exiting the "main" scope? 在下面的代码中,退出“主”范围时,“框5i”是否正确释放了? The wording on their pointer guide seems to indicate that variables with box types act as if there's an automatic "free()" call when the variable goes out of scope. 他们的指针指南上的措辞似乎表明,当变量超出范围时,具有框类型的变量的行为就像有一个自动的“ free()”调用一样。 However, if you "free()" on "a" in this code, it would only end up freeing the "box 8i" that is on the heap. 但是,如果在此代码中对“ a”使用“ free()”,则最终只会释放堆上的“ box 8i”。 What happens to the "box 5i" that "a" was originally pointing to? “ a”最初指向的“方框5i”会发生什么?

fn foo(a: &mut Box<int>) {
    *a = box 8i;
}

fn main() {
    let mut a = box 5i;
    println!("{}", a); // -> "5"
    foo(&mut a);
    println!("{}", a); // -> "8"
}

By default, overwriting a memory location will run the destructor of the old value. 默认情况下,覆盖内存位置将运行旧值的析构函数。 For Box<...> this involves running the destructor of the contents (which is nothing for an int ) and freeing the allocation, so if a has type &mut Box<T> , *a = box value is equivalent to (in C): 对于Box<...>这涉及到运行内容的析构函数(对于int不算什么)并释放分配,因此,如果a类型为&mut Box<T> ,则*a = box value等于(在C中):

T_destroy(**a);
free(*a);
*a = malloc(sizeof T);
**a = value;

In some sense, the answer to your question is yes, because the type system guarantees that *a = box ... can only work if a is the only reference to the old Box , but unlike most garbage collected/managed languages this is all determined statically, not dynamically (it is a direct consequence of ownership and linear/affine types). 从某种意义上说,您的问题的答案是肯定的,因为类型系统保证*a = box ...仅在a是对旧Box的唯一引用时才可以工作,但与大多数垃圾回收/托管语言不同,这就是全部静态而非动态确定(所有权和线性/仿射类型的直接结果)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM