Tim Diekmann
Tim Diekmann

Reputation: 8466

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?

Upvotes: 6

Views: 358

Answers (1)

Peter Hall
Peter Hall

Reputation: 58725

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.

Upvotes: 2

Related Questions