Same object different address. Why?

匆匆过客 提交于 2019-12-22 15:03:17

问题


Since both f and bar[42]! point to the same closure in the following code I would expect the unsafe pointers to point to the same address. They do not. Can anyone please explain why?

To clarify: I'm looking up the address returned by withUnsafePointer in Xcode using "view memory".

var bar = [Int : (() -> Void)]()

bar[42] = { print("foo") }

var f = bar[42]!

f() // prints "foo"

bar[42]!() // prints "foo"

withUnsafePointer(to: &f) { print( type(of: $0) ) ; print( $0 ) }
// UnsafePointer<(()) -> ()> 0x00007fff5fbff778 -> 0x100002100

withUnsafePointer(to: &bar[42]!) { print( type(of: $0) ) ; print($0) }
// UnsafePointer<(()) -> ()> 0x00007fff5fbff760 -> 0x100001d20

Update

I've updated the code to also print out the pointer's value:

var bar = [Int : (() -> Void)]()

bar[42] = { print("foo") }

var f = bar[42]!

f() // prints "foo"

bar[42]!() // prints "foo"

withUnsafePointer(to: &f) {
    print( type(of: $0.pointee) )
    print( $0 )
    $0.withMemoryRebound(to: Int.self, capacity: 1) {
        print("-> 0x\(String($0.pointee, radix: 16))")
    }
}

withUnsafePointer(to: &bar[42]!) {
    print( type(of: $0.pointee) )
    print($0)
    $0.withMemoryRebound(to: Int.self, capacity: 1) {
        print("-> 0x\(String($0.pointee, radix: 16))")
    }
}

Running this in Release mode gives the following output:

foo
foo
(()) -> ()
0x00007fff5fbff7d0
-> 0x100003f10
(()) -> ()
0x00007fff5fbff7d0
-> 0x100001f60

Which suggests that the compiler sees that f and bar[42]! are the same. What's confounding is that the same address can point to different copies of the same closure.


回答1:


&var is the address of the memory location that contains the address of the original memory location (i.e., it's a "pointer to a pointer").

Since ff & bar[] are two different variables, their adresses are differents too.

 ff(18)     bar(20)            coolvalue(84)
 [84]...[]...[84]...[].............[xxx]


来源:https://stackoverflow.com/questions/40178886/same-object-different-address-why

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!