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

后端 未结 2 1383
执笔经年
执笔经年 2021-01-24 07:09

I\'ve asked this question asking about the guarantees of the lifetime of a reference in a local variable and was referred to this thread in which the exact semantic

2条回答
  •  误落风尘
    2021-01-24 07:52

    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.

提交回复
热议问题