Why use `ptr::write` with arrays of `MaybeUninit`s?

旧街凉风 提交于 2021-02-06 15:53:13

问题


In the standard library, the documentation shows how to instantiate arrays of MaybeUninits:

let arr: [MaybeUninit<T>; N] =
    MaybeUninit::uninit().assume_init();

We know this is safe because the contract of MaybeUninit allows for uninitialized values. Next we are asked to use ptr::write(value) to initialize each element. But this requires unsafe code once again. We also know that overwriting a MaybeUninit is safe, because it doesn't drop anything. So why not just overwrite it like arr[i] = MaybeUninit::new(value)?


回答1:


let arr: [MaybeUninit<T>; N] = MaybeUninit::uninit().assume_init(); is just a shortcut.

arr[i] = MaybeUninit::new(value), in your example arr[i] is a MaybeUninit so your question is just about what style to use to mutate a vector. You could also do arr[i].write(value) that doesn't really change in practice but it's require nightly that why the doc don't use it. But you are right arr[i] = MaybeUninit::new(value) allow to override the value too without unsafe keyword and it's a perfectly defined behavior.

The thing you forget is that MaybeUninit is not really here to be used only inside Rust except very few case, Rust don't need it. We mostly use it when we dealing with ffi, so the exemple is not really a real word use case. So it can look strange. Here the author probably want to emulate a real word case where the array would be init outside Rust by using a raw pointer.



来源:https://stackoverflow.com/questions/56997322/why-use-ptrwrite-with-arrays-of-maybeuninits

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!