Function core::mem::forget [] [src]

pub fn forget<T>(t: T)

Leaks a value into the void, consuming ownership and never running its destructor.

This function will take ownership of its argument, but is distinct from the mem::drop function in that it does not run the destructor, leaking the value and any resources that it owns.

Safety

This function is not marked as unsafe as Rust does not guarantee that the Drop implementation for a value will always run. Note, however, that leaking resources such as memory or I/O objects is likely not desired, so this function is only recommended for specialized use cases.

The safety of this function implies that when writing unsafe code yourself care must be taken when leveraging a destructor that is required to run to preserve memory safety. There are known situations where the destructor may not run (such as if ownership of the object with the destructor is returned) which must be taken into account.

Other forms of Leakage

It's important to point out that this function is not the only method by which a value can be leaked in safe Rust code. Other known sources of leakage are:

Example

fn main() { use std::mem; use std::fs::File; // Leak some heap memory by never deallocating it let heap_memory = Box::new(3); mem::forget(heap_memory); // Leak an I/O object, never closing the file let file = File::open("foo.txt").unwrap(); mem::forget(file); }
use std::mem;
use std::fs::File;

// Leak some heap memory by never deallocating it
let heap_memory = Box::new(3);
mem::forget(heap_memory);

// Leak an I/O object, never closing the file
let file = File::open("foo.txt").unwrap();
mem::forget(file);