Swift 的内存管理 [英] Swift's memory management
问题描述
我对 Swift 的内存管理有点困惑.有人可以向我解释为什么 Kid1 总是停留在相同的内存地址吗?即使我执行 Kid1=kid2 或初始化一个新对象?
I'm a little confused regarding Swift's memory management. Can someone explain to me how come kid1 always stays at the same memory address? Even when I do kid1=kid2 or initialize a new object?
推荐答案
你的代码打印了 kid1
变量的内存位置,如果您为变量分配一个新值,这不会改变.
Your code prints the memory location of the kid1
variable,
and that does not change if you assign a new value to the variable.
如果 Kid
是一个引用类型(类),那么你可以使用ObjectIdentifier
获取类实例的唯一标识符变量引用:
If Kid
is a reference type (class) then you can use
ObjectIdentifier
to get a unique identifier for the class instance
that the variable references:
var kid1 = Kid(name: "A")
var kid2 = Kid(name: "B")
print(ObjectIdentifier(kid1)) // ObjectIdentifier(0x0000000100b06220)
print(ObjectIdentifier(kid2)) // ObjectIdentifier(0x0000000100b06250)
kid1 = kid2
print(ObjectIdentifier(kid1)) // ObjectIdentifier(0x0000000100b06250)
对象标识符恰好是指向的地址实例,但这是一个未记录的实现细节.如果您需要将对象引用转换为真正的指针然后你可以做(比较 How to cast self to UnsafeMutablePointer<Void> 快速输入)
The object identifier happens to be the address of the pointed-to instance, but that is an undocumented implementation detail. If you need to convert an object reference to a real pointer then you can do (compare How to cast self to UnsafeMutablePointer<Void> type in swift)
print(Unmanaged.passUnretained(kid1).toOpaque())
这篇关于Swift 的内存管理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!