什么是“弱引用”?在 KiokuDB 中?
KiokuDB 教程提到的弱引用到底是什么?
它们与“正常”参考有何不同?
What exactly are the weak references that KiokuDB tutorial mentions?
How do they differ from 'normal' references?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正常引用可防止所引用的事物被垃圾收集。弱引用与普通引用类似,但不会阻止垃圾回收。当对实体的最后一个普通引用被删除时,它会被垃圾收集,并且对它的任何弱引用都会变成
undef
。如果您有循环引用,这很有用。引用计数垃圾收集器(如 Perl 使用的)无法删除具有循环引用的内容,因为它们的引用计数永远不会变为 0。
例如,考虑一个树结构,其中父节点具有对其子节点的引用,而子节点具有对其子节点的引用。参考他们的父母。通过使子到父引用变得弱,当没有外部引用时,树将被自动垃圾收集。
在 Perl 中,可以使用 weaken 函数创建弱引用在 Scalar::Util 中。 Moose 还允许您将属性标记为 weak_ref。
A normal reference prevents the thing being referred to from being garbage collected. A weak reference is like a normal reference, but does not prevent garbage collection. When the last normal reference to an entity is removed, it gets garbage collected, and any weak references to it become
undef
.This is useful if you have circular references. A reference-count garbage collector (like Perl uses) cannot remove things with circular references, because their reference count never goes to 0.
For example, consider a tree structure, where parent nodes have references to their child nodes, and child nodes have a reference to their parent. By making the child-to-parent references weak, the tree will be automatically garbage collected when there are no external references to it.
In Perl, weak references can be created with the
weaken
function in Scalar::Util. Moose also allows you to mark attributes as weak_ref.