rust-lang / nomicon

The Dark Arts of Advanced and Unsafe Rust Programming
https://doc.rust-lang.org/nomicon/
Apache License 2.0
1.75k stars 258 forks source link

Dubious justification for using `NonNull` in `Arc` #323

Open samueltardieu opened 2 years ago

samueltardieu commented 2 years ago

In the page Implementing Arc and Mutex / Arc / Layout, the justification for using Arc is the following:

pub struct Arc<T> { ptr: *mut ArcInner<T>, }

This would compile, however it would be incorrect. First of all, the compiler will give us too strict variance. For example, an Arc<&'static str> couldn't be used where an Arc<&'a str> was expected.

To fix the first problem, we can use NonNull. Note that NonNull is a wrapper around a raw pointer that declares that:

  • We are variant over T
  • Our pointer is never null

What bugs me here is that ptr wouldn't need to be *mut ArcInner<T>, being *const ArcInner<T> would be enough and wouldn't have the variance problem. The justification for the pointer never being null is right though, but the one about variance is dubious.