See the following:
#![allow(unused_variables)]
use std::ptr;
// INTENTIONALLY not derive(Copy), even without a Drop impl
struct Foo {
bar: u32
}
impl Drop for Foo {
fn drop(&mut self) {
println!("dropped");
}
}
fn main() {
let n = Foo { bar: 123 };
let ptr = &n as *const Foo;
let n2 = (unsafe { ptr::read(ptr) }).bar;
}
Output:
dropped
dropped
As you can see, there's a double drop because of n2. I know that ptr::read
returns a shallow copy of Foo
, but is there any way to read a pointer to a non-Copy struct without dropping it? Of course, I can't use simple *ptr
because that only works for Copy structs.
I know I could wrap the result in ManuallyDrop
to stop that, but then to do anything with the pointer, I would need to go through a reference (via ManuallyDrop's Deref impl), and I explicitly do not want to handle references because my program will have aliasing in a single function, and, correct me if I'm wrong, but Rust does allow aliasing mutable raw pointers.