forget and drop functions
Below are the signatures for the
drop() and
forget() functions:
#![allow(unused)] fn main() { // std::mem::forget fn forget<T>(t: T) { let _ = std::mem::ManuallyDrop::new(t); } // std::mem::drop fn drop<T>(_x: T) {} }
-
Both
mem::forget()andmem::drop()take ownership of the valuet. -
Despite having the same function signature, they have opposite effects:
-
forget()usesManuallyDropto prevent the destructorDrop::drop()from being invoked.This is useful for scenarios such as implementing a drop bomb or otherwise opting out of destructor behavior.
Be careful though, since any resources the value exclusively owns such as heap allocated memory or file handles will remain in an unreachable state.
-
drop()is a convenience function for disposing of a value. Becausetis moved into the function, it is automatically dropped which triggers itsDrop::drop()implementation before the parent function returns.
-