具有可选内容的结构大小迅速

问题描述 投票:1回答:1

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

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

那不能被3整除! Int?的平均大小为9。怎么可能?

swift memory memory-management
1个回答
0
投票

[Int? aka Optional<Int>是一种enum类型,需要9个字节:8个字节为整数(如果我们使用的是64位平台),另加1个字节作为区分大小写。

此外,通过插入填充字节,每个整数在内存中都aligned到其自然边界(8字节)。

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

i1 i1 i1 i1 i1 i1 i1 i1      // 8 bytes for the first integer
c1                           // 1 byte for the first case discriminator
   p1 p1 p1 p1 p1 p1 p1      // 7 padding bytes
i2 i2 i2 i2 i2 i2 i2 i2      // 8 bytes for the second integer
c2                           // 1 byte for the second case discriminator
   p2 p2 p2 p2 p2 p2 p2      // 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个字节。

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

© www.soinside.com 2019 - 2024. All rights reserved.