The Rust language disallows unsafe code from moving-out non-copy types from behind a raw pointer, reporting a compilation error for the following program:
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 };
}
Compilation error:
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
What is the motivation of that error message? Is it because moving-out non-copy types from behind a raw pointer is error prone, even if the developer declared that he's expert enough to write unsafe code? Or is there some undefined behavior in the above program that I'm missing?