I have a type that occupies too much space to be allocated on the stack:
struct Foo {
lots_of_bytes: [u8; 1024 * 10],
bar: bool,
baz: isize,
}
There are two obvious solutions:
let foo = Box::new(Foo::new());
Or
struct Foo {
lots_of_bytes: Box<[u8; 1024 * 10]>,
bar: bool,
baz: isize,
}
To summarize, I either allocate the entire struct on the heap, or I can have the struct own the heap pointer. Is either of these solutions considered the "idiomatic" solution? Or is it strictly subjective or dependent on context?
Structs are allocated on the stack, if a local function variable, or on the heap as part of a class if a class member.
The best reason for heap allocation is that you cant always know how much space you need. You often only know this once the program is running. You might have an idea of limits but you would only want to use the exact amount of space required.
I think the question to ask yourself here is: will it ever make sense to place this struct in the stack? If the answer is no, you should probably enforce allocation on the heap. To achieve this, you have two alternatives:
lots_of_bytes: Box<[u8; 1024 * 10]>
.lots_of_bytes: [u8; 1024 * 10]
and ensure that all constructors of Foo
return Box<Foo
(so it becomes impossible to create a Foo
on the stack).In my opinion, the first alternative is much better:
Foo
shows clearly that the data must be stored on the heap.lots_of_bytes
, instead of the whole struct. This means that bar
and baz
would be placed on the stack, so you have less indirection.As for the second alternative, I can't think of any reason to prefer it and have never seen it in the wild.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With