【问题标题】:Size of struct with optionals in swiftswift中带有选项的结构的大小
【发布时间】:2019-10-19 12:38:25
【问题描述】:

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

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

不能被 3 整除!同时Int?的大小是9,怎么可能?

【问题讨论】:

    标签: swift memory memory-management


    【解决方案1】:

    Int? aka Optional<Int>enum 类型,需要 9 个字节:8 个字节用于整数(如果我们在 64 位平台上)加上 1 个字节用于区分大小写。

    此外,通过插入填充字节,每个整数在内存中对齐到其自然(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
    

    总共有 41 个字节。

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

    考虑了这个额外的填充
    print(MemoryLayout<SampleStruct>.size)    // 41
    print(MemoryLayout<SampleStruct>.stride)  // 48
    

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

    【讨论】:

      猜你喜欢
      • 2015-11-05
      • 1970-01-01
      • 1970-01-01
      • 2011-04-22
      • 1970-01-01
      • 1970-01-01
      • 2011-03-30
      • 2015-02-17
      • 1970-01-01
      相关资源
      最近更新 更多