- Learning Rust
- Paul Johnson Vesa Kaihlavirta
- 138字
- 2021-07-02 23:07:26
Deallocation
Unlike when memory is freed up on the stack, when you deallocate memory from the heap, you end up with holes in the heap. These are empty and can be reallocated to other variables. As with anything to do with memory, the reallocation is handled by the OS.
Deallocation is handled automatically by Rust with a style typically called Resource acquisition is initialization. This confusingly named concept means that resources (such as heap memory, but also other things such as file pointers) are allocated during object creation and released during object destruction. Object destruction in Rust happens when the binding goes out of scope. If you need to define custom destructors for your own objects, you can implement the std::ops::Drop() trait. It contains a single method, drop, which gets called when your object loses its last binding.