gpt4 book ai didi

objective-c - ARC 是否保证在最后一个强引用消失后立即释放对象?

转载 作者:可可西里 更新时间:2023-11-01 04:40:13 25 4
gpt4 key购买 nike

特别是,这种代码是否总是按预期工作(其中 MyResourceGuard 是一个在其 init 方法中锁定独占资源并在其 dealloc 方法中释放锁的对象):

NSLog(@"About to capture some exclusive resource.");
{
MyResourceGuard* guard = [MyResourceGuard new];
// Do something with the exclusive resource here.
}
// guard is out of scope, therefore its dealloc should have
// been called right away and the resource should already
// be free again at this point.

我在书籍和博客中读到的内容与例如Java 垃圾回收,一旦引用计数减少到零(而不是在它自己方便的时候),ARC 就会销毁对象,但我没有在 Apple 的任何官方文档中读到过这一点。如果那是真的,为什么我们需要在 ARC 中引入新的 @autoreleasepool 关键字?

在调试过程中,我总是看到对象被立即解除分配,除非在 try-catch-block 中引发异常,在这种情况下,实际上从未调用 dealloc(这是一个Mac 错误,或者只是这些可怕的 Objective C 怪癖之一?)。

最佳答案

没有。正如您的示例所示,您没有基于确定范围的 ObjC 对象销毁。

例如,这个程序可能会导致死锁:

{ MyResourceGuard* guard = [MyResourceGuard new]; }
{ MyResourceGuard* guard = [MyResourceGuard new]; }

如果您需要此功能,最好的办法是使用 C++ 类型 ( SBRM, RAII )——在 Objective-C++ 中也可用(但不适用于 objc 对象)。

它接近了,但是您只需要等到引用计数达到零才能调用 -dealloc,这就是保证失效的原因(通常 != always).这个问题实际上与为什么你永远不会依赖或使用 -retainCount(如果它可用)非常相似。示例:自动释放池、异常、对运行时或 ARC 生成代码的更改、编译器优化、使用具有不同代码生成标志的实现可能会导致 objc 对象的生命周期延长到超出范围。

更新

whole page on ARC at clang's site是关于这个主题的好读物——包括细节、保证(和缺乏保证),但特别是:

6.1. Precise lifetime semantics

In general, ARC maintains an invariant that a retainable object pointer held in a __strong object will be retained for the full formal lifetime of the object. Objects subject to this invariant have precise lifetime semantics.

By default, local variables of automatic storage duration do not have precise lifetime semantics. Such objects are simply strong references which hold values of retainable object pointer type, and these values are still fully subject to the optimizations on values under local control.

Rationale: applying these precise-lifetime semantics strictly would be prohibitive. Many useful optimizations that might theoretically decrease the lifetime of an object would be rendered impossible. Essentially, it promises too much.

A local variable of retainable object owner type and automatic storage duration may be annotated with the objc_precise_lifetime attribute to indicate that it should be considered to be an object with precise lifetime semantics.

Rationale: nonetheless, it is sometimes useful to be able to force an object to be released at a precise time, even if that object does not appear to be used. This is likely to be uncommon enough that the syntactic weight of explicitly requesting these semantics will not be burdensome, and may even make the code clearer.

即使您确实使用了 objc_precise_lifetime 属性,它也会应用于该强局部变量 的引用计数操作——而不是对象的生命周期。

关于objective-c - ARC 是否保证在最后一个强引用消失后立即释放对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13417287/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com