nomicon
nomicon copied to clipboard
Dubious justification for using `NonNull` in `Arc`
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 anArc<&'a str>
was expected.To fix the first problem, we can use NonNull<T>. Note that NonNull<T> 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.