下面代码测试 Copy on write
func run() {
let a = ["asdfdasoifljasodlfjasoldjfkoasldk", "asdfdasoifljasodlfjasoldjfkoasldk", "asdfdasoifljasodlfjasoldjfkoasldk"]
var b = a
print(String(format: "a: %p, a[0]: %p", a, a[0]))
print(String(format: "b: %p, b[0]: %p", b, b[0]))
b.append("asdfdasoifljasodlfjasoldjfkoasldk")
print(String(format: "b: %p, b[0]: %p", b, b[0]))
}
run()
// print:
// a: 0x60000092ee20, a[0]: 0x60000072d2c0
// b: 0x60000092ec60, b[0]: 0x60000072d410
// b: 0x60000092ebe0, b[0]: 0x60000072d3b0
值类型因为作为参数传递的时候已经是一个新指针。
Your code is printing the addresses of the array buffers (Array
is a special case when passing a value to a pointer parameter). However, in Swift 3, the compiler assumed that the presence of the &
operator meant that the buffer was being passed as mutable memory, so (unnecessarily) made it unique (by copying) before passing its pointer value, despite that pointer value being passed as an UnsafeRawPointer
. That's why you see different addresses.
Referrence
打印值类型可以通过这种方式打印
func address(_ p: UnsafeRawPointer) {
print(p)
}
func run() {
let a = ["asdfdasoifljasodlfjasoldjfkoasldk", "asdfdasoifljasodlfjasoldjfkoasldk", "asdfdasoifljasodlfjasoldjfkoasldk"]
var b = a
address(a)
address(b)
b.remove(at: 0)
address(b)
}
run()
网友评论