在 C++ 中打包嵌套结构 [英] Packing nested structs in C++

查看:47
本文介绍了在 C++ 中打包嵌套结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Visual Studio 2017,以下给出...

Using Visual Studio 2017, the following gives...

struct AAA // 15 bytes
{
    double d;
    short s;
    char a1;
    char a2;
    char a3;
    char s4;
    char s5;
};

struct BBB
{
    AAA d;
    char a4;
};

int main()
{
    std::cout << sizeof(AAA) << "\n"; // gives 16
    std::cout << sizeof(BBB) << "\n"; // gives 24
    getchar();
    return 0;
}

问题是……我如何让 sizeof(BBB) 为 16.

The Question is... how do I get sizeof(BBB) to be 16.

推荐答案

使用 #pragma pack(push, 1)#pragma pack(1) 强制编译器不要在 2 字节或 4 字节边界上排列结构成员,这使得处理器处理起来更容易、更快.因此该结构包含秘密填充字节来实现这一点.但这会因为填充而增加内存使用量.

Use #pragma pack(push, 1) or #pragma pack(1) to enforce compiler not to line up structure members on 2 byte or 4 byte boundaries which makes it easier and faster for the processor to handle. So the structure contains secret padding bytes to make this happen. But this increases memory usage because of padding.

它的精确解释这里

这篇关于在 C++ 中打包嵌套结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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