Swift class de-initialized at end of scope instead of after last usage

让人想犯罪 __ 提交于 2019-12-02 11:50:20

Let's analize how Swift works is respect to memory management:

  1. an object is deallocated when no are no more strong references to it
  2. a variable is "destroyed" when the scope where it's declared ends

Given the above two above facts, your Something instance is kept alive by the something variable which holds a strong reference to it until the end of scope, i.e. until the main function returns.

Try replacing let something = Something() by _ = Something() and you see that the expected behaviour that you want:

Something.init()
Something.deinit
in main()

Same behaviour occurs when holding a weak reference to the instance: weak var something = Something()

Note that there is a slight difference here between the something variable and the Something instance. The variable holds a reference to the instance, not the instance itself. Thus, the reference lifetime is the same as the variable lifetime, and this is what affect the instance's lifetime. Why the variable is not destroyed sooner, e.g. when the compiler detects it's no longer needed, I don't know.

If you had made your variable an optional and set it to nil, you would have explicitly told the compiler where you want the reference to be released.

e.g.

func main() {
    var something:Something? = Something()
    something = nil
    print("in main()")
}

Otherwise you are letting the compiler decide execution order on its own. In the same way that it could decide to execute any line of code out of order, it can also decide when to deallocate local variables.

In your example "something" is an non-optional local variable, so it is likely that the compiler will decide to allocate it on the stack. This will mean that the variable's value (on the stack) will hold the reference until the function returns.

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