gpt4 book ai didi

c++ - reinterpret_cast unsigned char* as uint64_t* - 这是 UB 吗?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:26:28 24 4
gpt4 key购买 nike

假设我们采用一个非常大的 unsigned char 数组。

std::array<uint8_t, 100500> blob;
// ... fill array ...

(注意:它已经对齐了,问题不在于对齐。)然后我们将其作为 uint64_t[] 并尝试访问它:

const auto ptr = reinterpret_cast<const uint64_t*>(blob.data());
std::cout << ptr[7] << std::endl;

转换为 uint64_t 然后从中读取对我来说看起来很可疑。

但是 UBsan,-Wstrict-aliasing 并没有触发它。Google 在 FlatBuffers 中使用了这种技术.此外,Cap'n'Proto 使用此 too .

这是未定义的行为吗?

最佳答案

您不能通过其他类型的左值访问 unsigned char 对象值。但相反是授权的,你可以通过一个unsigned char glvalue [basic.lval]访问任何对象的值:

If a program attempts to access the stored value of an object through a glvalue of other than one of the following types the behavior is undefined: [...]

  • a char, unsigned char, or std​::​byte type.

因此,为了 100% 符合标准,我们的想法是反转 reinterpret_cast:

uint64_t i;
std::memcpy(&i, blob.data() + 7*sizeof(uint64_t), sizeof(uint64_t));
std::cout << i << std::endl;

它会产生完全相同的 assembly .

关于c++ - reinterpret_cast unsigned char* as uint64_t* - 这是 UB 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48377412/

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