Rust Magical Box as Smartpointerfleeting
- External reference: https://doc.rust-lang.org/book/ch15-01-box.html
- External reference: https://doc.rust-lang.org/rust-by-example/std/box.html
- External reference: https://stackoverflow.com/questions/30352802/what-does-the-box-keyword-do
What does box x usually uses to allocate and free memory?
box x syntax depends on the following lang items:
owned_box on a Box struct to encapsulate the allocated pointer. This struct does not need a Drop implementation, it is implemented automatically by the compiler. exchange_malloc to allocate the memory. exchange_free to free the previously allocated memory.
Notice even on the standard library the Drop trait is not implemented by user-code. Indeed Box is a bit of a magical struct.
Values can be boxed (allocated on the heap) by creating a Box<T>. A box is a smart pointer to a heap allocated value of type T
When you have a large amount of data and you want to transfer ownership but ensure the data won’t be copied when you do so
All values in Rust are stack allocated by default