|
|
|
|
|
by reecko
1867 days ago
|
|
It is a pity that none of the replies to this comment has actually clarified your doubts... Assuming the absence of `const_cast`, C++'s `const` ensures that a data of the particular type doesn't get modified. That's it. Rust on the other hand, tracks and restricts aliasing. This means you can't get both a constant and non-constant reference to an object or anything owned by it (more precisely anything transitively reachable from it). This is helpful in preventing issues with invalid pointers (like iterator invalidation). For instance, if you have already borrowed an iterator (which is essentially a reference) you can't issue mutable operations on the vector (issuing mutable operations entails a mutable borrow), and that could potentially reallocate the backing memory of the vector. This property is also useful for preventing multiple writes to the same location in a multi-threaded application, making programs adhere to the single-writer principle by-construction. The downsides are that you might sometimes need to contort your code or your program architecture or perform mental/type gymnastics to write some trivially safe code or even use unsafe (or else lose performance) to satisfy the borrow checker. |
|