1

Updated Question:

Or I can ask this way: for every type T, if it's Copy, then there is no way for it to be moved, right? I mean is there any way like the std::move in C++ can move a copyable value explicitly?


Original Question:

Presume we have below a piece of Rust code, in this code, I defined a variable x holding an i32 value. What I want to do is to drop its value and invalidate it. I tried to use ptr::drop_in_place to drop it through a pointer, but it doesn't work, why?

fn main() {
    let mut x = 10;
    use std::ptr;
    unsafe {
        ptr::drop_in_place(&mut x as *mut i32);
    }
    println!("{}", x);  // x is still accessible here.
}
Jason Yu
  • 1,886
  • 16
  • 26
  • 1
    I'm not sure if what you're doing is safe or not, but I'm not sure what you want to achieve either. An `i32` doesn't have any [drop behavior](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=3b6e56e5132bd1801ec7b80b4f71b50a). – kmdreko Apr 24 '21 at 04:44
  • So, seems for every type T, if it's `Copy`, then there is no way for it to be moved, right? – Jason Yu Apr 24 '21 at 04:58

1 Answers1

3

For every type T, if it's Copy, then there is no way for it to be moved, right?

That is one way to word it. The semantics of Copy are such that any move leaves the original object valid.

Because of this, and that Drop and Copy are mutually exclusive traits, there's no way to "drop" a Copy. The traditional method of calling std::mem::drop(x) won't work. The only meaningful thing you can do is let the variable fall out of scope:

fn main() {
    {
        let x = 10;
    }
    println!("{}", x);  // x is no longer accessible here.
}

I mean is there any way like the std::move in C++ can move a copyable value explicitly?

The specifics of copying vs moving are quite different between C++ and Rust. All types are moveable in Rust, whereas its opt-in for C++. And moving and copying in Rust are always bitwise copies, there's no room for custom code. Moving in Rust leaves the source object invalid whereas its still useable as a value in C++.

I can go on, but I'll leave off one last bit: moving a primitive in C++ isn't different than a copy either.

kmdreko
  • 42,554
  • 6
  • 57
  • 106