繁体   English   中英

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

[英]Size of struct with optionals in swift

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

struct SampleStruct {
    var tt: Int?
    var qq: Int?
    var ww: Int?
}

不能被3整除! Int? 是 9. 怎么可能?

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

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

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

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

总共有 41 个字节。

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

print(MemoryLayout<SampleStruct>.size)    // 41
print(MemoryLayout<SampleStruct>.stride)  // 48

您可以在 Swift 文档的类型布局文档中找到详细信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM