Rust 语言不允许不安全的代码从原始指针后面移出非复制类型,报告以下程序的编译错误:
use std::cell::UnsafeCell;
struct NonCopyType(u32);
fn main() {
let unsafe_cell = UnsafeCell::new(NonCopyType(123));
let ptr = unsafe_cell.get();
// Disallowed, but the code will never access
// the uninitialized unsafe cell after this.
let _ = unsafe { *ptr };
}
编译错误:
error[E0507]: cannot move out of `*ptr` which is behind a raw pointer
--> src/main.rs:12:22
|
12 | let _ = unsafe { *ptr };
| ^^^^ move occurs because `*ptr` has type `NonCopyType`, which does not implement the `Copy` trait
For more information about this error, try `rustc --explain E0507`.
error: could not compile `playground` due to previous error
该错误消息的动机是什么?是因为从原始指针后面移出非复制类型很容易出错,即使开发人员声明他足够专家编写不安全的代码?或者上面的程序中是否有一些我遗漏的未定义行为?