简体   繁体   English

为什么__weak属性需要运行时支持

[英]Why do __weak properties require runtime support

In boost C++, a weak pointer is implemented as an observer to a shared (reference counted) pointer. 在boost C ++中,弱指针被实现为共享(引用计数)指针的观察者。

How are they implemented in objective-c, and why does this require runtime support? 它们如何在Objective-C中实现,为什么这需要运行时支持? (ie besides having compiler support, iOS 5 or above is required to use weak references) (即,除了具有编译器支持之外,还需要iOS 5或更高版本才能使用弱引用)

Objective-C weak references are set to nil when the object they point to is deallocated. 当释放它们所指向的对象时,Objective-C弱引用将设置为nil This is very convenient (it lets you solve reference cycles and avoid sending messages to deallocated objects), but it does require that the runtime track all weak references to objects and, when the object is finally deallocated, the runtime must nil out those references. 这非常方便(它使您可以解决引用循环并避免将消息发送到已释放的对象),但是它确实要求运行时跟踪对对象的所有弱引用,并且,当最终释放对象时,运行时必须淘汰那些引用。

Both of these things can only be done transparently by the Objective-C runtime. 这两件事只能由Objective-C运行时透明地完成。 Objective-C does not have the same flexibility that C++ does for implementing this kind of magic yourself in your own code. Objective-C不具备C ++自己在自己的代码中实现这种魔术的灵活性。

std::weak_ptr actually contains a pointer to a shared data-structure that holds book-keeping data and the referenced object. std :: weak_ptr实际上包含一个指向共享数据结构的指针,该数据结构保存簿记数据和引用的对象。 When the referenced object is destroyed this shared data is kept around so that weak_ptrs can see the book-keeping data that indicates the object is gone, and the weak_ptrs themselves don't have to be modified when the referenced object is deallocated. 当引用的对象被销毁时,共享数据将保留在周围,以便weak_ptrs可以看到表示该对象已消失的簿记数据,并且在释放引用的对象时不必修改weak_ptrs本身。

In Objective-C weak references do not point to some intermediate object that holds book-keeping data. 在Objective-C中,弱引用不指向某些保存簿记数据的中间对象。 They are normal pointers that point either to the actual referenced object, or to nil if the referenced object is gone. 它们是普通指针,指向实际引用的对象,如果引用的对象不存在,则指向nil。 Every __weak pointer has to be updated when some other part of the code releases the last non-weak pointer to an object. 当代码的其他部分释放指向对象的最后一个非弱指针时,必须更新每个__weak指针。 This requires runtime support. 这需要运行时支持。

In other words, Obj-C weak pointers are normal pointers except that there's compiler magic (which uses runtime support) working on them, whereas shared_ptrs and weak_ptrs are just wrappers that implement their own runtime support (in the smart pointers' constructors, assignment operators, destructors, etc.) around pointers. 换句话说,Obj-C弱指针是普通的指针,除了它们上有编译器魔术(使用运行时支持)外,而shared_ptrs和weak_ptrs只是实现自己的运行时支持的包装器(在智能指针的构造函数中,赋值运算符,析构函数等)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM