【问题标题】:C++ struct sizes are not making sense [duplicate]C ++结构大小没有意义[重复]
【发布时间】:2021-07-09 18:45:13
【问题描述】:

当我编译并运行以下代码时:

struct preferences {
    bool likesMusic : 1;
    bool hasHair : 1;
    bool hasInternet : 1;
    bool hasDinosaur : 1;
    unsigned int numberOfChildren : 4;
};

int main() {
    struct preferences homer;
    homer.likesMusic = true;
    homer.hasHair = false;
    homer.hasInternet = true;
    homer.hasDinosaur = false;
    homer.numberOfChildren = 3;
    
    printf("sizeof int: %ld bits\n", sizeof(int) * 8);
    printf("sizeof homer: %ld bits\n", sizeof(homer) * 8);
    printf("sizeof bool: %ld bits, sizeof unsigned int: %ld bits\n", sizeof(bool) * 8 , sizeof(unsigned int) * 8);
}

输出是:

sizeof int: 32 bits
sizeof homer: 32 bits
sizeof bool: 8, sizeof unsigned int: 32.

当我从首选项中注释掉 numberOfChildren 字段时,输出为:

sizeof int: 32 bits
sizeof homer: 8 bits
sizeof bool: 8, sizeof unsigned int: 32

这对我来说没有意义,因为 unsigned int 的大小从这个实验运行中推断为 24 位,因为在移除 numberOfChildren 字段后,homer 结构的大小从 32 位减少到 8 位。此外,输出本身包含 sizeof unsigned int: 32

您能提供的任何见解将不胜感激。谢谢。

我的设置是 Ubuntu 20.04,64 位,英特尔架构 Xeon Silver 16 核处理器。

【问题讨论】:

  • 您对结构体大小的期望究竟是什么?结果与此有何不同?
  • unsigned int 的大小被推断为 24 - 你的逻辑在两个方面存在缺陷:结构大小总是chars 的整数(像您正在使用的主流实现上的字节),并且您没有 unsigned int 成员,您有一个 4 位 bitfield 成员,其基本类型为 unsigned int。
  • @cigen:关于该副本的答案几乎没有提到位域,但这显然是这里的关键问题,如何获得一些布尔位域基于unsigned int 的位域到一个只有单个unsigned int 大小的结构中。 How is the size of a struct with Bit Fields determined/measured? 看起来像是覆盖了它,所以仍然是重复的。

标签: c++ c struct bit-fields


【解决方案1】:

默认情况下,编译器可以自行决定如何布局结构。它可能会选择添加“松弛字节”,因为它知道目标 CPU 如何从内存中检索数据——即所谓的“缓存行”。如果你想坚持将结构“打包”成最少的字节数,你必须明确地这样做,接受生成的目标代码可能效率较低。 (也许,“效率大大降低了!”)

【讨论】:

  • 加上 slack bytes,你的意思是 padding bits?
  • @franji1 这不正是我在回答中所解释的吗?这些仍然被称为填充位。
  • 试过 __attribute__((packed)) ,以及将字段 unsigned int numberOfChildren 设置为首选项中的第一个字段成员。
猜你喜欢
  • 2010-12-22
  • 1970-01-01
  • 2012-01-22
  • 1970-01-01
  • 1970-01-01
  • 2014-11-17
  • 2012-10-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多