如何在swift中找出"optional"的内存区域?

How to find out the memory area of an "optional" in swift?

我正在研究CoW。 我知道在数组和字典的背后,CoW 是有效的。

为了检查这一点,我通过打印查看了内存区域。

var array1 = [1,2,3] 
array1.withUnsafeBufferPointer { (point) in
    print(point)      // 0x00006000006080e0
}
var array2 = array1 //  0x00006000006080e0
array2.append(4)   // 0x0000600002351ba0 <- changed

如何查看可选类型的内存区域?在我看的会议上,作者说在可选的引擎盖下,CoW 也可以工作,我想看看。

.withUnsafeBufferPointer - for optional types does not work!

var optionalInt: Int?
optionalInt = 1                 // memory area?
var optionalInt2 = optionalInt // memory area?
optionalInt2 = 2              // memory area?

您需要使用withUnsafePointer(to:)

var optionalInt: Int?
print("optionalInt = \(optionalInt)")
withUnsafePointer(to: optionalInt, { pointer in
    print("optionalInt: \(pointer)")
})
optionalInt = 1
print("optionalInt = \(optionalInt)")
var optionalInt2 = optionalInt
print("optionalInt2 = \(optionalInt)")
withUnsafePointer(to: optionalInt2, { pointer in
    print("optionalInt2: \(pointer)")
})
optionalInt2 = 2
print("optionalInt2 = \(optionalInt)")

输出:

optionalInt = nil

optionalInt: 0x00007ffee58ede90

optionalInt = Optional(1)

optionalInt2 = Optional(1)

optionalInt2: 0x00007ffee58ede28

optionalInt2 = Optional(1)

作为大卫 - 正确的决定。但是你可以 运行 进入一个错误。你所有的可选值都将指向内存中的同一个区域。这就是发生在我身上的事情:

为避免这种情况,请这样检查:

func pointer(object: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer {
    return object
}

var optional1: Int?
var optional2: Int?

print( pointer(object: &optional1) ) // 0x0000000108f68090
print( pointer(object: &optional2) ) // 0x0000000108f680a0