4 ms·
> Values that are forgotten without being dropped can leak resources or even cause undefined behavior! I thought that Rust had given up on considering mem::for
by rav 6y ago
> Values that are forgotten without being dropped can leak resources or even cause undefined behavior!
I thought that Rust had given up on considering mem::forget to be undefined behavior? I think this sentence should be softened to just say "cause other unwanted behavior", since "undefined behavior" is such a precise concept.
- saghm 6y agoYes, you're correct. From the documentation on std::mem::forget[1]: "forget is not marked as unsafe, because Rust's safety guarantees do not include a guarantee that destructors will always run. For example, a program can create a reference cycle using Rc, or call process::exit to exit without running destructors. Thus, allowing mem::forget from safe code does not fundamentally change Rust's safety guarantees. That said, leaking resources such as memory or I/O objects is usually undesirable. The need comes up in some specialized use cases for FFI or unsafe code, but even then, ManuallyDrop is typically preferred. Because forgetting a value is allowed, any unsafe code you write must allow for this possibility. You cannot return a value and expect that the caller will necessarily run the value's destructor." [1]: https://doc.rust-lang.org/std/mem/fn.forget.html#safety https://doc.rust-lang.org/std/mem/fn.forget.html#safety
- kzrdude 6y agoIt hasn't officially been formulated this way, but whatever owns a value will have the power to decide if its destructor should run or not.