这是我的 Playground 代码。
import Foundation
func printAddress<T>(anyObj: T,message: String = "") {
var copy = anyObj
withUnsafePointer(to: ©) {
print("\(message) value \(copy) has memory address of: \($0)")
}
}
class Account {
var balance: Int = 0
init(balance: Int) {
self.balance = balance
}
}
func deposit(amount: Int, into account: inout Account) {
account.balance += amount
printAddress(anyObj: account, message: "After deposit") //0x00007fff569ba188
printAddress(anyObj: acct,message: "Address of acct within the deposit free function") //0x00007fff59eb6188
//What makes both memory addresses are same inside the fucntion?
}
func verify(account: Account) -> Bool{
printAddress(anyObj: acct,message: "Address of acct within the verify function") //0x00007fff5a39a188
//Again surprisingly same as address used in deposit function copied account var. Optimization?
return account.balance > 0
}
var acct = Account(balance: 10)
printAddress(anyObj: acct,message:"Before deposit 20") // Print 0x00007fff518751f8
deposit(amount: 20, into: &acct)
verify(account: acct)
printAddress(anyObj: acct,message:"After and deposit and verify completed") //// Print 0x00007fff518751f8
我有 2 个我不清楚的观察结果。
- 为什么它为
account
(复制的实例)和acct
(原始acct)打印相同的内存地址 - 当我在验证方法调用中打印内存地址时。为什么它再次与先前方法调用中使用的地址相同。是编译器优化的原因吗?
最佳答案
发生的事情是您总是在 printAddress()
函数中打印 copy
变量的地址。您没有打印您传入的参数的地址,即使那是您想要的。
当输入 printAddress()
时,copy
变量的地址始终是超出当前堆栈指针的某个常量固定偏移量,但堆栈指针会根据调用 printAddress()
时代码的嵌套深度。
要查看另一个值,创建一个调用 printAddress()
的函数 foo()
,然后从 调用
。foo()
>验证()
同样,它始终是您在调用 print()
时看到的 copy
变量的内存地址。
如果你想打印传递给 printAddress()
的东西的内存地址,你需要去掉临时的:
func printAddress<T>(anyObj: inout T, message: String = "") {
withUnsafePointer(to: &anyObj) {
print("\(message) value \(anyObj) has memory address of: \($0)")
}
}
现在调用:
printAddress(anyObj: &acct, message: "message")
从任何地方,您都会看到相同的值。
关于ios - inout 参数的外部实例的 Swift 内存地址与复制的实例相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41918294/