3
votes

According to https://doc.rust-lang.org/stable/rust-by-example/std/box.html,

All values in Rust are stack allocated by default. Values can be boxed (allocated on the heap) by creating a Box. A box is a smart pointer to a heap allocated value of type T. When a box goes out of scope, its destructor is called, the inner object is destroyed, and the memory on the heap is freed.

So if I have a std::vec::Vec<MyStruct> and I add a lot of structs, does this mean that the structs are stack allocated? How can this be possible? I can only have a collection of things if they're on the heap. Things on the stack are made in compile time, since I understand.

1
If you are using structs that's gonna depend on their internals. Vec for instance stores its internal data on the heap.Dulguun Otgon

1 Answers

6
votes

A Box is one way of allocating on the heap, but it is not the only way. Other data structures, including Vec, store their data on the heap. So in this case, as you create each instance of MyStruct initially it will be on the stack, but as soon as you push it onto the Vec, it will be moved to the heap. At least, that's conceptually how it works; depending on the specific situation and the compiler optimization settings, Rust may be able to avoid physically writing to the stack, instead writing directly to the heap.