为什么当int64_t更改为int32_t时类的大小会增加 [英] Why class size increases when int64_t changes to int32_t

查看:215
本文介绍了为什么当int64_t更改为int32_t时类的大小会增加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的第一个示例中,我有两个使用int64_t的位域.当我编译并获得类的大小时,我得到8.

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;
    int64_t second : 24;
};

int main()
{
    std::cout << sizeof(Test); // 8
}

但是当我将第二个位数更改为int32_t时,该类的大小将增加一倍,达到16:

But when I change the second bitfeild to be a int32_t the size of the class doubles to 16:

class Test
{
    int64_t first : 40;
    int32_t second : 24;
};

int main()
{
    std::cout << sizeof(Test); // 16
}

在GCC 5.3.0和MSVC 2015上都会发生这种情况.但是为什么?

This happens on both GCC 5.3.0 and MSVC 2015. But why?

推荐答案

在您的第一个示例中

int64_t first : 40;
int64_t second : 24;

firstsecond都使用单个64位整数的64位.这将导致类的大小为单个64位整数.在第二个示例中,您有

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;

两个独立的位字段存储在两个不同的内存块中.您使用64位整数中的40位,然后使用另一个32位整数中的24位.这意味着您至少需要12个字节(此示例使用8位字节).您最有可能看到的额外4个字节将填充,以使类在64位边界上对齐.

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.

这篇关于为什么当int64_t更改为int32_t时类的大小会增加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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