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
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
Show replies
Replying to and
As an example, if you're looping over a collection in C++, if you accidentally modify the collection, you probably end up with a use-after-free. C++ code does far more allocations/copies than Rust rather than using lightweight references largely because it's hard to do it right.
1
2
Show replies