51 points · by lukastyrychtr · 5y ago · 14 comments
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.
"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
They can be called concurrently with each other, but the call to `UnsafeCell::get()` is guarded by an acquire-release latch for precisely that reason. This is already explained in the article.
>I'm scratching my head on the syntax. There is no read() method on MaybeUninit. Also, the type passed to the write() method is wrong. I need to clone this and see if I can compile this.
read() and write() are functions of `*mut T`, which is what is returned by `UnsafeCell::get()`