3 ms·
I guess what they mean is that the Vec would allocate heap space, and you could steal the allocation for your object to make the Box? You'd need to create this
by tialaramex 4y ago
I guess what they mean is that the Vec would allocate heap space, and you could steal the allocation for your object to make the Box? You'd need to create this MyType manually and then tell Box what you made unsafely with like Box::from_raw()
It feels like a better way to do that directly with Box is Box::<MyType>::new_zeroed() which will make you a Box<MaybeUninit<MyType>> full of zero bytes. If MyType is definitely valid when made entirely of zero bytes and you're sure of that, you can unsafely assume_init() to have the MaybeUninit resolve to an actual MyType.
[[ If you lied, now everything is on fire, I did warn you that you need to be sure and it is an unsafe function ]]
If MyType is very much not valid if consisting entirely of zero bytes well, new_uninit() gives you memory in unspecified (must not be read) state, you can properly initialise it and then assume_init() as before - but all the extra work kinda sucks, and in either case clearly it would be nicer to just write what you meant and have it work.
- klodolph 4y agoI think the commenter made a guess that I was boxing an array, which is a good guess, it just happens to be wrong in this case. Maybe that will work in the future—I don’t use nightly Rust, so for now, new_zeroed() won’t work. The basic problem is “I want to allocate something large on the heap” and it doesn’t seem like I should need to use nightly builds or unsafe{} to do it.
- tialaramex 4y ago> I don’t use nightly Rust, so for now, new_zeroed() won’t work That's a completely fair observation. The main thing I want stabilised is a single niche for custom types. I would take more if offered but experience says that every extra little thing doubles the discussion time, so, one niche is all I need, and Rust guarantees this exists in some form so even if a later mechanism does - say - fancy non-contiguous niches, I just want one value ASAP. https://github.com/rust-lang/rfcs/pull/3334 https://github.com/rust-lang/rfcs/pull/3334 > “I want to allocate something large on the heap” and it doesn’t seem like I should need to use nightly builds or unsafe{} to do it. The former makes sense to me, the latter (a requirement to use unsafe) I can see there can be cases where the compiler has to do a lot of contortions to safely but optimally mint the type in place in the heap and just writing the unsafe case is reasonable. I don't know anything about your type so I can't judge.
- sli 4y agolet heap_value = vec![the_struct]; Based on another comment addressing this, I don't think the original commentor was making assumptions about the shape of your data.
- klodolph 4y agoThis doesn’t actually work, it will still overflow the stack. The vec! macro will just copy its arguments into the heap; the arguments are still on the stack to begin with.