本文介绍了为什么将`ptr :: write`与MaybeUninit`s的数组一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在标准库中,文档显示了如何实例化数组 MaybeUninit s:

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

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

我们知道这是安全的,因为 MaybeUninit 的协定允许使用未初始化的值.接下来,要求我们使用 ptr :: write(value)初始化每个元素.但这又需要 unsafe 代码.我们也知道覆盖 MaybeUninit 是安全的,因为它不会 drop 任何东西.那么为什么不像 arr [i] = MaybeUninit :: new(value)那样覆盖它呢?

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)?

推荐答案

让arr:[MaybeUninit< T> ;;N] = MaybeUninit :: uninit().assume_init(); 只是一个快捷方式.

arr [i] = MaybeUninit :: new(value),在您的示例中, arr [i] MaybeUninit 只是关于用来改变向量的样式.您还可以做 arr [i] .write(value),实际上在实践中并没有真正改变,但是每晚都需要为什么文档不使用它.但是您是正确的 arr [i] = MaybeUninit :: new(value)允许在没有不安全关键字的情况下也覆盖该值,并且这是一个完美定义的行为.

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.

您忘记的是,除极少数情况外, MaybeUninit 并没有真正在Rust内部仅用于 ,Rust不需要它.在处理ffi时,我们通常会使用它,因此示例并不是真正的单词用例.因此它看起来很奇怪.在这里,作者可能想模拟一个真实的单词情况,即使用原始指针在Rust外部初始化数组.

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.

这篇关于为什么将`ptr :: write`与MaybeUninit`s的数组一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 00:42