簡體   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