UnwindSafety questions

Trait std::panic::UnwindSafe - documentation


  1. Why is explicit implementation of UnwindSafe for HashMap and BTreeMap needed if items built from UnwindSafe things are automatically UnwindSafe?
  2. Is BTreeMap UnwindSafe implementation broken, because it should require K, V to be UnwindSafe, not RefUnwindSafe?
  3. &mut T is !UnwindSafe, so why can *mut T be UnwindSafe?

This is easy: an automatic implementation would bind K and V to UnwindSafe instead of RefUnwindSafe, since Box is auto implemented with UnwindSafe. It looks like this happens because Box holds Unique, and Unique holds PhantomData, and PhantomData magically gets UnwindSafe.

No idea what's up with the fixme. I'm guessing BTreeMap used to be auto-implemented with those constraints, and when the struct changed, the auto-impl changed, so they added this manual impl to fix that.

For 3, you need unsafe to use *mut anyway, so there's little chance of accidentally assuming the value (if it exists) is valid.

  1. Because they contain something not automatically UnwindSafe, for example the addition in the link below. Note how it was already "wrong" under the automatic implementation.
  2. @drewtato's guess is correct.
  3. The usual reasoning with raw pointers is they're completely inert unless you use unsafe anyway.

Everything potentially protective about these traits are "best effort", since you can just disable them without unsafe at the point of their primary use case. So upholding semver is generally going to take priority. Some consider it a failed experiment, which is why you'll see references to deprecation or "disarming" them here and there.


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.