官术网_书友最值得收藏!

Garbage collecting time and ownership

If you're used to any of the .NET languages, you'll be more than accustomed to the garbage collector (GC). Essentially, when all references to an object have gone out of scope, the object's heap allocation is freed up by the garbage collector. The garbage collector comes around every once in a while, basically checks through the whole space of allocated memory to see if something isn't used anymore, and removes such content from memory; in other words, the garbage left behind by a deallocated pointer is collected and removed.

Rust has a primitive garbage collector in the form of a reference counted container, Rc<T>. For most cases, it's not required though, as Rust uses a system known as ownership for allocation.

Up to this point, when we created a variable, we created variables that mostly live on the stack. These have a very short life span. When we create an object that lives on the heap, we create a single variable that points to it, but then we can have any number of objects point to it, or even through a copy of the pointer, have the copy become the base and free up the original. It gets messy and deallocation of the heap memory can lead to a variety of memory issues.

We can wrap any type in a generic container, Box<T>. This creates an owned pointer in Rust, which can only have a single owner, and when that pointer goes out of scope, the memory is automatically freed. In this way, Rust prevents a large number of the problems that we see in other languages. The point of this owned box is that we can hand out the box to other functions, thus being able to return heap allocated variables.

主站蜘蛛池模板: 枣庄市| 仁怀市| 额尔古纳市| 饶平县| 仁化县| 晋中市| 名山县| 车险| 渑池县| 顺平县| 广宗县| 固镇县| 林州市| 陆丰市| 宁夏| 乌拉特中旗| 大新县| 尼木县| 崇文区| 靖远县| 南投市| 喜德县| 雷州市| 钦州市| 青岛市| 乐业县| 威远县| 龙川县| 太和县| 怀柔区| 十堰市| 浦县| 麻江县| 铁力市| 托里县| 敦化市| 柳州市| 大丰市| 安泽县| 双柏县| 科技|