发布于 2014-12-26 21:54:00
我认为垃圾回收是防止手动释放动态分配内存的任何进程。
那么铁锈确实有“垃圾收集”!
fn make_stuff() {
// Allocate memory on the heap and store `true` in it
let thing = Box::new(true);
// Allocate memory on the heap and store 1000 numbers in it.
let things = vec![42; 1000];
} // Look Ma! No manual deallocation!当thing和things超出作用域时(在本例中,是在方法的末尾),那么它们分配的内存将被释放给您。
Rc和Arc允许更多的灵活性;您应该让他们的医生读一读才能知道更多。
除了@Manishearth的回答之外,还有以下细节(强调我的):
在其最后一个所有者的生命周期结束时自动释放
在许多垃圾收集语言中,垃圾收集与您的代码的其余部分无关。在“铁锈”中,将知道重新分配的地点。
考虑到这个Java:
public static ArrayList alpha()
{
return new ArrayList();
}
public static void beta()
{
alpha(); // Unused result
}我不相信你能肯定地说什么时候ArrayList将从内存中删除。在等效的Rust代码中,您知道Arc或Rc一旦超出作用域就会被销毁。
发布于 2014-12-29 11:47:21
发布于 2014-12-26 21:25:21
Rc没有循环集合。如果您创建了一个引用循环,那么您很可能会使程序崩溃,因为它试图增加重新计数。
虽然从技术上讲,这也是一个垃圾收集器,但它并不是一个普遍有用的工具,因为您对它可以包含的类型有限制。
https://stackoverflow.com/questions/27662120
复制相似问题