假设我有一个向量,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/