幸运快三

swift – 保证部门变量中援用的生命周期

在 中,我可以应用ARC机制来治理历程外部资源的生命周期,由于类的实例可以事后扫除初始化.这与Java Runtime之类的情形组成较量,在Java Runtime中,当残余群集器群集工具时,实例被去初始化,这不克不及保证在界说的时间窗口中发生.

幸运快三但是,当部门变量援用这些实例时,Swift语言和运转时对实例生命周期着实着实切保证是甚么?例如.当部门变量持有对它的唯一援用时,实例能够被释放的最早点是甚么?

不才面的示例中,我培植了一个类的实例,并在部门变量中存储对它的援用.

public final class Something {
    init() { print("something.init()") }
    deinit { print("something.deinit()") }
}

func useSomething() {
    let something = Something()
    print("useSomething()")
}

useSomething()

在我打印useSomething()以后不应用该变量,但是在挪用print()以后deinit运转不合:

$swift run -c release
something.init()
useSomething()
something.deinit()

似乎援用总是在变量超出规模时递减.在do块中包装变量声明会更改序次:

func useSomething() {
    do { let something = Something() }
    print("useSomething()")
}
$swift run -c release
something.init()
something.deinit()
useSomething()

这个订单是保证还是可以用不合的编译器或优化级别更改?

我对此感兴趣的启事是我想在面向工具的Swift API中包装C API,并欲望应用Swift类和援用计数自动治理应用C API分配的资源的生命周期.假定C API的每次应用都须要对其操作的资源的援用,那么这很有用,由于我知道Swift实例将至少存活到对实例所代表的资源阻拦操作的最后一次挪用.

幸运快三但是一些API应用全局状态来选择资源,而且对API的后续挪用不须要援用要转达的资源,而是隐式地对所选资源阻拦操作. OpenGL的glDrawElements()隐式应用5或10个这样的资源(极点数组,着色器,帧缓冲区,纹理……).

Swift不保证工具的生命周期直到
比来的规模的末尾,例如,参见
Swift服装网服装论坛中的以下主题:

>
>

假定声明你可以应用:

幸运快三Evaluates a closure while ensuring that the given instance is not destroyed before the closure returns.

为了这个目的.至于理由,
州:

The lack of such a guarantee, which is very seldom actually useful
anyhow, is what allows us to turn costly copies (with associated
refcount traffic and, often CoW allocation and copying fallout) into
moves, which are practically free. Adopting it would basically kill our
幸运快三 performance story for CoW.

和在统一个帖子中:

幸运快三Yeah, if you want to vend resources managed by an object to consumers outside of that object like this, you need to use withExtendedLifetime to keep the object alive for as long as you’re using the resources. A cleaner way to model this might be to put the class or protocol in control of handling the I/O to the file handle, instead of vending the file handle itself, so that the ownership semantics fall out more naturally:

相关文章
相关标签/搜索