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

标签 vector rust swap undefined-behavior

假设我有一个向量,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 的神器,并且您有一个正在尝试解决的实际问题。

关于vector - Rust 中是否未定义将未初始化的值临时交换到向量中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31778955/

相关文章:

c++ - 带有 vector 的重载流插入运算符

c++ - 汽车出了什么问题?

c++ - C++ 中字符串 vector 的 reserve() 函数

rust - 您如何将文本文件中的行读入i32s元组的向量中?

forms - 使用 Rocket 中的结构解析 HTTP 多部分 POST

C++内联运算符重载,引用当前对象

memory - 虚拟内存的最大大小是多少?

python - 更快的 3D 矩阵操作 - Python

java - 一种在数组中的两个索引之间交换位置的方法

struct - 在以下上下文中如何解决 "lifetime of reference outlives lifetime of borrowed content"?