How to drop `v` without running `ops::Drop::drop()`

I am performing like following:

struct A {
  a:u8
}
impl Drop for A {
  fn drop(&mut self) {
    // this is not needed to be dropped
    let another = A {a: self.a};
  }
}

So I got stack overflowing. but forget leaks A here, drop and drop_in_place run the drop again. How can I do to drop another without running drop again?

let another = std::mem::ManuallyDrop::new(A {a: self.a});

1 Like

If I don't call drop on the ManuallyDrop and it leaves the scope, is it leaked on the stack?

I see, thanks for your patience. I've confirmed this by following example.

  let mut b = &0u8;
  {
    let a = std::mem::ManuallyDrop::new(200u8);
    b = &*a; // `a` does not live long enough
             // borrowed value does not live long enough
  }
  println!("{b}");

If you wrap a heap allocated object in ManuallyDrop (directly or indirectly) and doesn't manually drop the object, it will leak memory.
Because the stack stores a pointer to the object, and that the pointer is destroyed doesn't mean the object is destroyed.

3 Likes

Why are you making a temporary copy of the object being dropped, only to then drop that temporary? What are you actually trying to do here?