Search code examples
pointersmemoryrustreferenceundefined-behavior

Is writing over a not deinitialized object undefined behavior?


struct C { ... }
impl C {
  pub fn new() { ... }
}
fn main() {
  let mut x = C::new();
  unsafe { *(&x as *mut C) = C::new(); } // We are overwriting an object without disposing old value.
}

Is it undefined behavior?

If it is, how should I dispose the old object (x) before the unsafe assignment?


Solution

  • It is not undefined bevaviour

    struct C;
    impl C {
        pub fn new() -> Self {
            C
        }
    }
    
    impl Drop for C {
        fn drop(&mut self) {
            println!("C is Drop!");
        }
    }
    
    fn main() {
        let mut x = C::new();
        println!("before reassignment !");
        unsafe {
            *(&mut x as *mut C) = C::new();
        } // We are overwriting an object without disposing old value.
        println!("after reassignment !");
    }
    

    will print:

    before reassignment !
    C is Drop!
    after reassignment !
    C is Drop!