Why class size increases when int64_t changes to int32_t

前端 未结 4 1023
不知归路
不知归路 2021-02-11 19:31

In my first example I have two bitfields using int64_t. When I compile and get the size of the class I get 8.

class Test
{
    int64_t first : 40;
         


        
4条回答
  •  感动是毒
    2021-02-11 20:21

    In your first example

    int64_t first : 40;
    int64_t second : 24;
    

    Both first and second use the 64 bits of a single 64 bit integer. This causes the size of the class to be a single 64 bit integer. In the second example you have

    int64_t first : 40;
    int32_t second : 24;
    

    Which is two separate bit fields being stored in two different chunks of memory. You use 40 bits of the 64 bit integer and then you use 24 bit of another 32 bit integer. This means you need at least 12 bytes(this example is using 8 bit bytes). Most likely the extra 4 bytes you see is padding to align the class on 64 bit boundaries.

    As other answers and comments have pointed out this is implementation defined behavior and you can/will see different results on different implementations.

提交回复
热议问题