gpt4 book ai didi

objective-c - __bridge_transfer 的描述相互矛盾;它避免双重保留吗?

转载 作者:行者123 更新时间:2023-11-29 13:31:57 25 4
gpt4 key购买 nike

迈克·阿什说:

When __bridge_transfer is used in a cast, it tells ARC that this object is already retained, and that ARC doesn't need to retain it again. Since ARC takes ownership, it will still release it when it's done.

Clang 文档说:

(__bridge_transfer T) op casts the operand, which must have non-retainable pointer type, to the destination type, which must be a retainable object pointer type. ARC will release the value at the end of the enclosing full-expression, subject to the usual optimizations on local values.

Clang 文档中没有任何地方说 __bridge_transfer 避免了双重保留。它只是说该对象在未来的某个时间被释放。

为什么这很重要?考虑以下代码片段:

NSString *value = (__bridge_transfer NSString *)CFPreferencesCopyAppValue(CFSTR("someKey"), CFSTR("com.company.someapp"));

CFStringRef 以 +1 的 retainCount 开始。当它被分配给 value 时,CFStringRef 再次被保留,因为默认情况下,value 被强引用。这导致双重保留。在作用域的末尾,-release 被发送到 value,但不存在其他任何东西来平衡来自 CFPreferences*Copy*AppValue 的挥之不去的保留,从而导致内存泄漏.

__bridge_transfer 如何避免双重保留?

最佳答案

Clang 的文档同意 Mike Ash 的观点。它说它执行强制转换,对象在作用域结束时被释放。转换期间不执行保留。

基本上,(__bridge_transfer T) 会导致该值被视为类型为 T 的已拥有值,就像调用 [T new] 一样 将返回类型为 T 的已拥有值。

关于objective-c - __bridge_transfer 的描述相互矛盾;它避免双重保留吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11620836/

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