小编Dom*_*324的帖子

C/C++ 中嵌套结构的尾随填充 - 有必要吗?

这更多的是一个理论问题。我熟悉填充和尾随填充的工作原理。

struct myStruct{
    uint32_t x;
    char*    p;
    char     c;
};

// myStruct layout will compile to
// x:       4 Bytes
// padding: 4 Bytes
// *p:      8 Bytes
// c:       1 Byte
// padding: 7 Bytes
// Total:   24 Bytes
Run Code Online (Sandbox Code Playgroud)

之后需要有填充x,以便*p对齐,并且之后需要有尾部填充c,以便整个结构体大小可以被 8 整除(为了获得正确的步幅长度)。但考虑这个例子:

struct A{
    uint64_t x;
    uint8_t  y;
};

struct B{
    struct A myStruct;
    uint32_t c;
};

// Based on all information I read on internet, and based on my tinkering
// with …
Run Code Online (Sandbox Code Playgroud)

c c++ padding compiler-optimization structlayout

22
推荐指数
1
解决办法
1648
查看次数

标签 统计

c ×1

c++ ×1

compiler-optimization ×1

padding ×1

structlayout ×1