gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 06:50:54 24 4
gpt4 key购买 nike

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

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);
据我所知,一般来说 SAR 说我们不能通过不同类型的指针访问(读取或写入)数据 - 除非我们使用字符类型的指针。
但是,在上面的代码中,我们使用非字符类型( float* )的指针来读取或写入(可能)字符类型( uint8_t )的数据,我认为这是非法的。
我对么?

最佳答案

However, in the above code we use a pointer of a non-character type (float*) to read or write data of (probably) a character type (uint8_t), which I think is illegal.

Am I correct?


是的。

Is the following code legal in terms of the Strict Aliasing Rule (and in general)?


不。

除了指针别名,另一个考虑是 float 的对齐要求。比 uint8_t更严格.是否有疑问 uint8_t* allocateBuffer(arg)返回满足 float对齐的指针.

关于c++ - 带有 uint8_t 的 reinterpret_cast 是否违反了严格别名规则?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63797386/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com