Rust的Arc和Rc类型与垃圾收集有什么不同? [英] How are Rust's Arc and Rc types different from having garbage collection?
问题描述
Rust编程语言,首先版本说,Rust没有垃圾收集器:
它在没有垃圾收集器的情况下维护这些目标
然而,在 据我所知,这正是指针在像Python这样的垃圾收集语言中的工作方式。 我认为垃圾集合是任何阻止需要手动释放动态分配的内存的进程。然而,我认为我不明白Rust指南认为是垃圾收集的方式。 我认为垃圾回收是防止需要手动释放动态分配内存的任何进程。 然后Rust确实有垃圾回收! 当 除了@ Manishearth的回答,还有这个细节(重点是我的): 在最后所有者的生命周期结束时自动释放 在许多垃圾收集语言中,垃圾收集与您的其他代码在带外发生。在Rust中,释放的位置是已知的。 给定这个Java: 我不相信你可以用当ArrayList将从内存中移除时确定性。在等价的Rust代码中,您知道 The Rust Programming Language, first edition says that Rust does not have a garbage collector: It maintains these goals without having a garbage collector However, in discussing choosing your guarantees it also says: As far as I understand, this is exactly how pointers work in a garbage-collected language like Python. I consider garbage collection to be any process which prevents the need for manual deallocation of dynamically-allocated memory. I think I don't understand what the Rust guide considers to be garbage collection however. I consider garbage collection to be any process which prevents the need for manual deallocation of dynamically-allocated memory Then Rust does have "garbage collection"! When In addition to @Manishearth's answer, there's also this detail (emphasis mine): automatically freed at the end of its last owner's lifetime In many garbage-collected languages, garbage collection happens out-of-band with the rest of your code. In Rust, the location of deallocation will be known. Given this Java: I do not believe that you can say with certainty when the ArrayList will be removed from memory. In the equivalent Rust code, you know that an 这篇关于Rust的Arc和Rc类型与垃圾收集有什么不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
Rc< T>
是引用计数的指针。换句话说,这可以让我们拥有多个指向相同数据的拥有指针,当所有指针超出范围时,数据将被丢弃(析构函数将运行)。
$ $ p $ $ $ $ $ $ $ $ $ $ $ //在堆上分配内存并在其中存储`true`
让thing = Box :: new(true);
//在堆上分配内存并在其中存储1000个数字。
let things = vec![42; 1000];
} //看马!没有手动释放!
thing
和事情
超出范围(在这种情况下,在方法结束时),那么他们分配的内存将被释放。
Rc
和 Arc
允许比此更灵活;您应该阅读其文档以了解更多信息。
public static ArrayList alpha()
{
return new ArrayList();
public static void beta()
{
alpha(); //未使用的结果
}
Arc
或 Rc
一旦超出范围就会被销毁。
Rc<T>
is a reference counted pointer. In other words, this lets us have multiple "owning" pointers to the same data, and the data will be dropped (destructors will be run) when all pointers are out of scope.
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
and things
go out of scope (in this case, at the end of the method), then the memory they had allocated will be freed for you.Rc
and Arc
allow more flexibility than this; you should give their docs a read to know more.
public static ArrayList alpha()
{
return new ArrayList();
}
public static void beta()
{
alpha(); // Unused result
}
Arc
or Rc
will be destructed as soon as it goes out of scope.