My understanding is that the following code has undefined behaviour in C++ due to something called "strict aliasing rule".
#include <cstdint>
enum Foo : int16_t {};
void test(Foo& foo) {
reinterpret_cast<int16_t&>(foo) = 42;
}
In particular, a C++ compiler may omit the assignment altogether because it is allowed to assume that the int16_t&
returned by the reinterpret_cast
doesn't point to the same memory as foo
(of type Foo&
) because their types are different.
My question is, does Rust have something akin to the C++ "strict aliasing rule"? In other words, does the following, equivalent Rust code have undefined behaviour?
#[repr(i16)]
enum Foo { Dummy }
unsafe fn test(foo: &mut Foo) {
*std::mem::transmute::<&mut Foo, &mut i16>(foo) = 42;
}
EDIT:
There's an unrelated issue with the above Rust example code in that test
creates a non-existing enum variant. So, here's the same code with a quick fix:
#[repr(i16)]
enum Foo { Dummy, Yummy = 42 }
unsafe fn test(foo: &mut Foo) {
*std::mem::transmute::<&mut Foo, &mut i16>(foo) = 42;
}