且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么弱指针有用?

更新时间:2023-11-13 23:47:10

典型的用例是存储额外的对象属性。假设你有一个拥有固定成员集合的类,并且从外部你想添加更多成员。所以你创建一个字典对象 - >属性,其中的键是弱引用。然后,字典不会阻止密钥被垃圾收集;删除对象也应触发WeakKeyDictionary中的值的删除(例如通过回调)。

I've been reading up on garbage collection looking for features to include in my programming language and I came across "weak pointers". From here:

Weak pointers are like pointers, except that references from weak pointers do not prevent garbage collection, and weak pointers must have their validity checked before they are used.

Weak pointers interact with the garbage collector because the memory to which they refer may in fact still be valid, but containing a different object than it did when the weak pointer was created. Thus, whenever a garbage collector recycles memory, it must check to see if there are any weak pointers referring to it, and mark them as invalid (this need not be implemented in such a naive way).

I've never heard of weak pointers before. I would like to support many features in my language, but in this case I cannot for the life of me think of a case where this would be useful. For what would one use weak pointer?

A typical use case is storage of additional object attributes. Suppose you have a class with a fixed set of members, and, from the outside, you want to add more members. So you create a dictionary object -> attributes, where the keys are weak references. Then, the dictionary doesn't prevent the keys from being garbage collected; removal of the object should also trigger removal of the values in the WeakKeyDictionary (e.g. by means of a callback).