impl Drop for Foo {
fn drop(..) {
self.cleanup();
self.free_memory();
}
}
even if `self.cleanup()` panics. When that happens, `self.free_memory` will never be called, and memory will be leaked if `panic=unwind`, which is the default behavior. If there is a `catch_unwind` somewhere, these leaks will grow over time.The same code in C++:
~foo() {
this->cleanup();
this->free_memory();
}
does not have this issue, because if `this->cleanup()` unwinds, that unwind makes `~foo` abort, because `~foo` is `noexcept(true)` by default.In Rust, one cannot make `Drop::drop` be "nounwind", so to emulate C++'s behavior, one needs to write:
impl Drop for Foo {
fn drop(...) {
if let Err(_) = cath_unwind(|| {
self.cleanup(); self.free_memory();
}) {
abort();
}
}
}
or use a `DropGuard` to make sure that `self.free_memory()` is called if `self.cleanup` throws, etc.Destructors being fallible are very weird things. In C++, destructors are infallible (at least by default). Rust supports fallible destructors, with all its cost (every time an object is dropped, doing this can fail, adding another "return" point from your function), yet minimal or zero value.
At least, I couldn't find any examples in the Rust book / reference / rust-by-example that show in which situations unwinding from a destructor is a good thing to do.