3 ms·
> Let us ask the question: Is there anything inherently unsafe about multiple (even mutable) references to an object? I think the problem with your example her
by Measter 3y ago
> Let us ask the question: Is there anything inherently unsafe about multiple (even mutable) references to an object?
I think the problem with your example here is that it's a bit simplistic. In your example, if we drop the concept of ownership, sure it's not unsafe they can both point to the same allocation. But multiple mutable references can absolutely be a big issue. For example:
pub enum Thing {
AA(i32),
BB(String),
}
pub fn foo() {
let mut thing = Thing::BB(String::from("Hello"));
let Thing::BB(str_ref) = &mut thing else {unreachable!()};
bar(&mut thing);
println!("{str_ref}");
}
fn bar(_: &mut Thing) { ... };
Without knowing the body of `bar` it's not possible to determine whether `foo` is sound. `bar` could change the enum to the `AA` variant, at which point `str_ref` is now pointing at an integer and some padding bytes, not a String. We've violated type safety, and read uninitialized memory both in the enum itself and in the now-dropped heap allocation.
- akiarie 3y ago> Without knowing the body of `bar` it's not possible to determine whether `foo` is sound. This is literally the point we're making in the article. Note that what protects you from violating type safety is not the ownership rules, but the ability to propagate these rules by annotating `bar`. So we're proposing a direct focus on this propagation.