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

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.

主站蜘蛛池模板: 乌鲁木齐县| 庆安县| 宁津县| 新晃| 皋兰县| 正镶白旗| 尉犁县| 商都县| 拜城县| 东乌| 绥阳县| 永善县| 开原市| 康乐县| 泌阳县| 庆阳市| 洮南市| 舞阳县| 兴城市| 英超| 桃源县| 清河县| 台东市| 聂拉木县| 馆陶县| 永年县| 古浪县| 郯城县| 托克托县| 富源县| 开封市| 正定县| 绥宁县| 甘孜| 汉川市| 新巴尔虎左旗| 五家渠市| 临桂县| 盖州市| 安徽省| 岱山县|