gpt4 book ai didi

c++ - 读取和写入结构的填充位

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:56:15 25 4
gpt4 key购买 nike

我有以下 32 位对齐结构和必要的填充以确保 i32 数据成员的 32 位对齐:

struct
{
std::uint8_t i8;
std::uint32_t i32;
} x, y = {0};

写入填充位是否具有明确定义的行为?例如,在代码中:

reinterpret_cast<std::uint32_t&>(x) = 256u;

填充部分总是写入和读取为1吗?

另一个问题:

对于y,填充总是初始化为0吗?

我的理解是 C++ [dcl.init] 声明:

To zero-initialize an object or reference of type T means: if T is a non-union class type, each non-static data member and each base-class subobject is zero-initialized and padding is initialized to zero bits

但是,我在 Microsoft 编译器 (vc++ v120) 中没有看到这种行为,示例:

reinterpret_cast<std::uint32_t&>(y) == 0u

不计算为 true。它可能是缺少的功能,或者我误解了标准中的短语。

最佳答案

我不是填充方面的专家,但我认为不可能保证任何填充,至少在没有特殊且可能特定于实现的选项的情况下是不可能的。

将 reinterpret_cast 用于除转换回原始指针以外的任何事情都不是定义的行为。 reinterpret_cast 意味着您在代码中做了一些狡猾的事情。

这个问题讲的是padding初始化成什么 Is zero initialization of structures guaranteed to wipe padded areas?

关于c++ - 读取和写入结构的填充位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18370170/

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