外部参数的外部实例的Swift内存地址与复制的实例相同

时间:2017-01-29 06:33:28

标签: ios swift swift3

这是我的游乐场代码。

import Foundation

func printAddress<T>(anyObj: T,message: String = "") {
  var copy = anyObj
  withUnsafePointer(to: &copy) {
    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个观察结果,我不清楚。

  1. 为什么它为account(复制的实例)和acct(原始的acct)打印相同的内存地址
  2. 当我在验证方法调用中打印内存地址时。为什么它再次与先前方法调用中使用的地址相同。这是由编译器优化引起的。

1 个答案:

答案 0 :(得分:3)

发生的事情是,您始终在copy功能中打印printAddress()变量的地址。您打印您传入的参数的地址,即使这是您的意图。

copy变量的地址总是在输入printAddress()时超过堆栈指针的某个常量固定偏移量,但是堆栈指针的变化取决于代码在{{{}时的嵌套程度。 {1}}被调用。

要查看其他值,请创建一个调用printAddress()的函数foo(),然后从printAddress()调用foo()

同样,它始终是您在verify()被调用的时间点看到的copy变量的内存地址。

如果你想打印传递给print()的东西的内存地址,你需要摆脱临时的:

printAddress()

现在打电话:

func printAddress<T>(anyObj: inout T, message: String = "") { withUnsafePointer(to: &anyObj) { print("\(message) value \(anyObj) has memory address of: \($0)") } }

从任何地方,您都会看到相同的价值。