带有 uint8_t 的 reinterpret_cast 是否违反了严格别名规则?

Avi*_*ohn 5 c++ strict-aliasing c++14

根据严格别名规则(以及一般情况),以下代码是否合法?

const int size = 1024;
uint8_t* buffer = allocateBuffer(size);
float* float_pointer = reinterpret_cast<float*>(buffer);
std::fill(float_pointer, float_pointer + size / sizeof(float), 1.5f);
Run Code Online (Sandbox Code Playgroud)

据我所知,一般来说 SAR 说我们不能通过不同类型的指针访问(读取或写入)数据 - 除非我们使用字符类型的指针。

但是,在上面的代码中,我们使用非字符类型(float*)的指针来读取或写入(可能)字符类型(uint8_t)的数据,我认为这是非法的。

我对么?

eer*_*ika 5

但是,在上面的代码中,我们使用非字符类型(float*)的指针来读取或写入(可能)字符类型(uint8_t)的数据,我认为这是非法的。

我对么?

是的。

根据严格别名规则(以及一般情况),以下代码是否合法?

不。


除了指针别名之外,另一个考虑因素是 的对齐要求float比 的更严格uint8_t。是否uint8_t* allocateBuffer(arg)返回满足 对齐方式的指针存在疑问float