C ++ bitfield包装与bools [英] C++ bitfield packing with bools

查看:250
本文介绍了C ++ bitfield包装与bools的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚做了一个测试与位字段,结果是令人惊讶的我。

I've just done a test with bitfields, and the results are surprising me.

class test1 {
public:
    bool test_a:1;
    bool test_b:1;
    bool test_c:1;
    bool test_d:1;
    bool test_e:1;
    bool test_f:1;
    bool test_g:1;
    bool test_h:1;
};

class test2 {
public:
    int test_a:1;
    int test_b:1;
    int test_c:1;
    int test_d:1;
    int test_e:1;
    int test_f:1;
    int test_g:1;
    int test_h:1;
};

class test3 {
public:
    int test_a:1;
    bool test_b:1;
    int test_c:1;
    bool test_d:1;
    int test_e:1;
    bool test_f:1;
    int test_g:1;
    bool test_h:1;
};

结果是: -

sizeof(test1) = 1   // This is what I'd expect. 8 bits in a byte
sizeof(test2) = 4   // Reasonable. Maybe padded out to the size of an int.
sizeof(test3) = 16  // What???

这是你期望的还是编译器错误? (Codegear C ++ Builder 2007,btw ...)

Is this what you'd expect, or a compiler bug? (Codegear C++ Builder 2007, btw...)

推荐答案

您的编译器已将整个test3的所有成员安排在整数大小边界。一旦块用于给定类型(整数位字段或布尔位字段),编译器就不会再分配任何不同类型的位字段,直到下一个边界。

your compiler has arranged all of the members of test3 on integer size boundaries. Once a block has been used for a given type (integer bit-field, or boolean bit-field), the compiler does not allocate any further bit fields of a different type until the next boundary.

我怀疑这是一个错误。这可能与您系统的底层架构有关。

I doubt it is a bug. It probably has something to do with the underlying architecture of your system.

编辑:

c ++编译器将如下分配存储器中的位字段:将顺序分配相同类型的几个连续位字段成员。一旦需要分配新类型,它将与下一个逻辑内存块的开始对齐。下一个逻辑块将取决于您的处理器。一些处理器可以对齐到8位边界,而其他处理器只能对齐到16位边界。

c++ compilers will allocate bit-fields in memory as follows: several consecutive bit-field members of the same type will be allocated sequentially. As soon as a new type needs to be allocated, it will be aligned with the beginning of the next logical memory block. The next logical block will depend on your processor. Some processors can align to 8-bit boundaries, while others can only align to 16-bit boundaries.

在test3中,每个成员的类型都不同在它之前,所以内存分配将是8 *(系统上的最小逻辑块大小)。在你的情况下,最小块大小是两个字节(16位),因此test3的大小是8 * 2 = 16。

In your test3, each member is of a different type than the one before it, so the memory allocation will be 8 * (the minimum logical block size on your system). In your case, the minimum block size is two bytes (16-bit), so the size of test3 is 8*2 = 16.

8位块,我预计大小为8。

On a system that can allocate 8-bit blocks, I would expect the size to be 8.

这篇关于C ++ bitfield包装与bools的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆