在 Rust 中是否未定义临时将未初始化的值交换到向量中?

Is it undefined in Rust to temporarily swap uninitialized values into a vector?

假设我有一个矢量,v: Vec<T>,长度为 5,容量为 10。以下是否会调用未定义的行为?

let p = v.as_mut_ptr(); 
unsafe {
    std::mem::swap(p, p.offset(5));
    std::mem::swap(p.offset(5), p);
}

是的,这是未定义的。来自 Rust Reference 的第 6.1.3.2.3 节:

The following is a list of behavior which is forbidden in all Rust code, including within unsafe blocks and unsafe functions. Type checking provides the guarantee that these issues are never caused by safe code.

  • ...
  • Reads of undef (uninitialized) memory
  • ...

p.offset(5) 是未定义的内存,您必须读取它才能交换它。

当然,我真的不明白你的问题有什么意义,因为即使它被定义了,该操作也是空操作。我怀疑这是 XY Problem 的人为产物,并且您有一个您正在尝试解决的实际问题。