相同对象的地址不同。为什么? [英] Same object different address. Why?

查看:158
本文介绍了相同对象的地址不同。为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于 f bar [42]!指向下面代码中的相同闭包不安全的指针指向同一个地址。
他们没有。任何人都可以解释为什么?

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?

澄清:我使用view memory查找withUnsafePointer在Xcode中返回的地址。

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

这表明编译器看到 f bar [42]!是相同的。混淆的是,同一个地址可以指向同一闭包的不同副本。

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.

推荐答案

& var 是包含原始存储器位置的地址的存储器位置的地址(即,它是指针的指针)。

&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").

因为 ff & bar [] 是两个不同的变量,它们的地址也不同。

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

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

这篇关于相同对象的地址不同。为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆