3 ms·
Yes, understood. But in Rust (without going through unsafe code), you can't write a program that will produce a reference to a u16 that overlaps with half of a
by not2b 4y ago
Yes, understood. But in Rust (without going through unsafe code), you can't write a program that will produce a reference to a u16 that overlaps with half of a global u32. In C/C++ you could cast a pointer that way and turn it into a reference, but the compiler is allowed to assume, even though you wrote that, that the u16 (unsigned short) reference can't refer to some particular global u32 (unsigned int), and if it has it in a register it won't reload it. The program has undefined behavior (you could use unions and get implementation-defined behavior, which will depend on little-endian vs big-endian).
- tialaramex 4y ago> without going through unsafe code None of this matters in Rust without unsafe. Pointers technically exist outside unsafe, but you can't do very much with them (you cannot, for example, dereference a pointer). And yes, Rust says that the attempted type pun you describe, which you would need unsafe to create, is Undefined Behaviour. > you could use unions and get implementation-defined behavior Type punning with unions is also Undefined Behaviour in C++. The sanctioned way to perform type punning is to memcpy() the data from type A to type B. C++ 20 provides a built-in way to ask for this to be done std::bit_cast