Conversation

I don’t know Rust, so I was wondering how this would look in C++, does anyone have an example?
Quote Tweet
Conceptually, the thing that makes Rust different from modern C++ (and other languages) is the "alias xor mutable" guideline, enforced by the borrow check. You could write C++ that way, but in practice nobody does. It's much stricter than just using smart pointers.
Show this thread
12
15
Replying to
In Rust, you can only hold either one mutable reference or a bunch of immutable references to x. For example: int x = 42; x += 1; // ok const int& r1 = x; // ok x += 1; // Error const int& r2 = x; // ok int& r3 = x; // Error
1
6
Replying to and
or int x = 42; int& r1 = x; // ok r1 += 1; // ok const int& r2 = x; // error int& r3 = x; // error This restriction roots out the possibility of race conditions. And as far as I know, no other major languages (not just C++) have enforcement in this way.
1
3
Replying to and
Mutable references can invalidate other references by freeing allocations, changing the variant in a tagged union, etc. The issue isn't only data races. So, for example, a mutable reference to a std::vector can push to it resulting in use-after-free via other references, etc.
2
3
Similarly, a mutable reference to a tagged union (including very common ones in Rust like Option or Result) can switch Some(T) to None, etc. which would invalidate references. There are a lot of ways for a mutable reference to cause memory corruption via overlapping references.
1
3
So, for example, if you have &mut (int, int), you can trivially get a separate mutable reference to each integer. Similarly, you can split a mutable slice (&mut [T]) into two non-overlapping ones with split_at_mut along with other approaches. &mut T happily coerces to &T too.
3