Why does a function have long-term write access to all of its in-out parameters?

谁说胖子不能爱 提交于 2021-01-27 20:21:46

问题


According to the chapter of "Memory Safety" in the Swift Programming Language Guide (for Swift 4.2), there is a sentence "A function has long-term write access to all of its in-out parameters." https://docs.swift.org/swift-book/LanguageGuide/MemorySafety.html

I created a new command line tool project to verify it in Xcode 10.1.

var stepSize = 1

func increment(_ number: inout Int) {
  print(stepSize)
}

increment(&stepSize)

I expect the output to be 1, but the actual output is a crash log "Simultaneous accesses to 0x100587430, but modification requires exclusive access."

I know this is a conflict about accessing in-out parameters, but I don't know why this happens. Why does a function have long-term write access to all of its in-out parameters?


回答1:


A consumer of this API sees func increment(_ number: inout Int), but not the implementation. It can only assume that increment(_:) makes writes to the parameters, because it can, in principle.

Even if the function implementation doesn't currently do any writes, the possibility is there, so the compiler has to assume the worst case scenario. Imagine if some client code was allowed to compile against this, treating is as if it's read only (because at the time, it may be the case). What should happen to the client code when someone adds number += 1 to the function body?

This is similar to having a function that declares it can throw, whose actual implementation doesn't throw. The compiler still treats it as throwing, and necessitates the error be handled with some variant of try.



来源:https://stackoverflow.com/questions/54394980/why-does-a-function-have-long-term-write-access-to-all-of-its-in-out-parameters

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