为什么弱指针有用? [英] Why are weak pointers useful?

查看:161
本文介绍了为什么弱指针有用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读垃圾收集,寻找包含在我的编程语言中的功能,并且遇到了弱点。从此处


弱指针就像指针一样,
除了弱
指针的引用不会阻止垃圾
集合,弱指针必须
在使用
之前检查它们的有效性。


弱指针与
垃圾收集器进行交互,因为它们所涉及的内存
可能实际上仍然是
是有效的,但包含一个不同于
的对象,而不是在创建弱
指针时。因此,无论何时
垃圾收集器回收内存,
都必须检查是否存在指向它的任何
弱指针,并且
将它们标记为无效(这不必是
以这种天真的方式实施)。


我从来没有听说过弱指针。我想用我的语言来支持许多功能,但在这种情况下,我不能为了我的生活而想到一个可能有用的情况。对于那些使用弱指针的应用程序?

解决方案

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

这篇关于为什么弱指针有用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆