swift中带有选项的结构的大小

And*_* M. 2 memory memory-management swift

奇怪的调用结果MemoryLayout<SampleStruct>.size。它在以下结构上返回 41。

struct SampleStruct {
    var tt: Int?
    var qq: Int?
    var ww: Int?
}
Run Code Online (Sandbox Code Playgroud)

不能被3整除!的同时大小Int?是 9。怎么会呢?

Mar*_*n R 5

Int?akaOptional<Int>是一种enum类型,需要 9 个字节:8 个字节用于整数(如果我们在 64 位平台上)加上一个字节用于大小写鉴别器。

此外,通过插入填充字节,每个整数在内存中与其自然(8 字节)边界对齐

所以你的结构在内存中看起来像这样:

i1 i1 i1 i1 i1 i1 i1 i1      // 8 bytes for the first integer
c1 p1 p1 p1 p1 p1 p1 p1      // 1 byte for the first case discriminator,
                             // ... and 7 padding bytes
i2 i2 i2 i2 i2 i2 i2 i2      // 8 bytes for the second integer
c2 p2 p2 p2 p2 p2 p2 p2      // 1 byte for the second case discriminator
                             // ... and 7 padding bytes
i3 i3 i3 i3 i3 i3 i3 i3      // 8 bytes for the third integer
c3                           // 1 byte for the third case discriminator
Run Code Online (Sandbox Code Playgroud)

这总共有 41 个字节。

如果SampleStruct值连续存储在数组中,则在元素之间插入额外的填充以确保每个值都从 8 字节边界开始。步幅考虑了这种额外的填充

print(MemoryLayout<SampleStruct>.size)    // 41
print(MemoryLayout<SampleStruct>.stride)  // 48
Run Code Online (Sandbox Code Playgroud)

您可以在 Swift 文档的Type Layout文档中找到血腥的细节。