3 ms·
> Consequently, you need a way to tell the compiler that the object it thinks exists at an address no longer does, and that object has neither been moved nor de
by LegionMammal978 2y ago
> Consequently, you need a way to tell the compiler that the object it thinks exists at an address no longer does, and that object has neither been moved nor destroyed, and that there may be an unrelated object at that address that was never constructed.
If anything, Rust is even more expressive than C++ in this regard: it has no concept at all of "an object at an address". You can (unsafely) cast a pointer from any type to any other type and read it, as long as the underlying memory is properly initialized. And if you're in a context where you know it will always be valid, or if you can check the validity at runtime, you can put a safe wrapper over the conversion.
For instance, the safe function str::from_utf8() converts a byte-array pointer into a string pointer, after checking that the encoding is correct. Nothing in memory is changed, and the old and new pointers form two different views that can be used simultaneously. And it's not magic: you could copy its implementation yourself, and your function would be just as valid as the standard-library version. Contrast with C++, where all memory must have one single type at any time, regardless of how much laundering you do.
The only kinds of semantic "ownership" in Rust are access restrictions caused by the aliasing rules (which just depend on the pointers in use, not on objects in memory), and local variables and temporaries being dropped at the end of their scope (if they haven't been moved elsewhere). All the high-level lifetime rules of safe Rust are built on top of those semantic rules, and a smidgeon of unsafe Rust can subvert them as necsssary.