Description
The doc comment for mem::forget
currently reads:
Any resources the value manages, such as heap memory or a file handle, will linger forever in an unreachable state. However, it does not guarantee that pointers to this memory will remain valid.
The second sentence was introduced in #53503, with this rationale:
it's not obvious
mem::forget
does not guarantee leaking of memory: memory of stack-allocated objects and values partially moved out ofBox
will still be freed
In other words, it's intended to be a warning about these two footguns:
let byte = 42_u8;
let raw_ptr = &byte as *const u8;
std::mem::forget(byte);
let forty_two = unsafe { *raw_ptr };
let raw_ptr;
{
let boxed_byte = Box::new(42u8);
raw_ptr = &*boxed_byte as *const u8;
std::mem::forget(*boxed_byte);
}
let forty_two = unsafe { *raw_ptr };
To me, the current language is too broad. It implies that heap allocations owned by a value passed to mem::forget
may be invalidated. For example, it implies that the following code is unsound:
let s = format!("example");
let s_ptr = s.as_ptr();
std::mem::forget(s);
let lowercase_e = unsafe { *s_ptr };
Opening an issue rather than a PR because I'm not sure how best to rephrase this.