1

I've got a simple resource which uses MaybeUninit and unsafe for external reasons:

pub struct Resource<'a, T> {
    repr: std::cell::RefMut<'a, std::mem::MaybeUninit<T>>
}
impl<'a, T> Drop for Resource<'a, T> {
    fn drop(&mut self) {
        unsafe { // Safety: `MaybeUninit<T>` is always initialized here.
            std::ptr::drop_in_place(self.repr.as_mut_ptr());
        }
    }
}

I guess, if T::drop() panics, the RefMut gets leaked, poisoning its RefCell. How can I prevent this and would it be idiomatic to do so? The documentation states:

Given that a panic! will call drop as it unwinds, any panic! in a drop implementation will likely abort.

but that "likely" doesn't make it clear enough whether I should expect (and can handle) this scenario.

passing_through
  • 1,778
  • 12
  • 24
  • "but that "likely" doesn't make it clear enough whether I should expect (and can handle) this scenario." a double panic (panic during unwinding) is a hard abort, you literally can't handle it. – Masklinn Oct 22 '20 at 09:50
  • @Masklinn what about a "single" panic occurring in an ordinary `drop` (which isn't caused by a panic)? – passing_through Oct 22 '20 at 09:59
  • `drops` get called during unwinding, regardless of whether the unwinding was triggered from a `drop` or from other non-drop code. – Masklinn Oct 22 '20 at 10:04
  • In general you should write `Drop::drop` assuming that any other `drop` you invoke, implicit or explicit, will not panic. For other cases, you may check `std::thread::panicking()` and avoid panicking there. – rodrigo Oct 22 '20 at 13:47

0 Answers0