Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is ManuallyDrop<Box<T>> with mem::uninitialized defined behavior?

I have an array with [ManuallyDrop<Box<T>>] which is filled lazily. To realize this, I "initialize" the array with ManuallyDrop::new(mem::uninitialized()).

Is this well-defined behavior as long as I only call ManuallyDrop::drop() on initialized elements?

like image 692
Tim Diekmann Avatar asked Oct 19 '18 13:10

Tim Diekmann


1 Answers

Provided that you do not read from uninitialized memory or create pointers to it, then this should not be UB.

You will need to do some careful bookkeeping to disallow access to uninitialized items, and only drop initialized ones. Adding a new item where there is uninitialized memory needs to be done with ptr::write(), to avoid an invalid drop on the underlying memory. But if you overwrite an existing valid value, then you should not use ptr::write because you need that value to be correctly dropped.

like image 135
Peter Hall Avatar answered Nov 13 '22 22:11

Peter Hall