What is VC++ doing when packing bitfields?

前端 未结 5 693
既然无缘
既然无缘 2020-12-03 23:01

To clarify my question, let\'s start off with an example program:

#include 

#pragma pack(push,1)
struct cc {
    unsigned int a   :  3;  
            


        
5条回答
  •  遥遥无期
    2020-12-03 23:31

    MSVC++ always allocates at least a unit of memory that corresponds to the type you used for your bit-field. You used unsigned int, meaning that a unsigned int is allocated initially, and another unsigned int is allocated when the first one is exhausted. There's no way to force MSVC++ to trim the unused portion of the second unsigned int.

    Basically, MSVC++ interprets your unsigned int as a way to express the alignment requirements for the entire structure.

    Use smaller types for your bit-fields (unsigned short and unsigned char) and regroup the bit-fields so that they fill the allocated unit entirely - that way you should be able to pack things as tightly as possible.

提交回复
热议问题