本文介绍了弱引用 - 它们有多有用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我最近一直在考虑一些自动内存管理的想法 - 具体来说,我一直在考虑实现基于引用计数的内存管理器.当然,每个人都知道循环引用会扼杀幼稚的引用计数.解决方案:弱引用.就我个人而言,我讨厌以这种方式使用弱引用(还有其他更直观的方法来处理这个问题,通过循环检测),但这让我开始思考:弱引用还有什么用处?

So I've been mulling over some automatic memory management ideas lately - specifically, I've been looking at implementing a memory manager based on reference counting. Of course, everyone knows that circular references kill naive reference counting. The solution: weak references. Personally, I hate using weak references in this way (there are other more intuitive ways of dealing with this, via cycle detection), but it got me thinking: where else could a weak reference be useful?

我认为它们存在一定是有原因的,特别是在具有跟踪垃圾收集功能的语言中,它们不受循环引用陷阱的影响(C#和Java是我熟悉的,Java甚至有三种弱引用!).然而,当我试图为它们找到一些可靠的用例时,我几乎只是得到了使用它们来实现缓存"之类的想法(我在 SO 上见过几次).我也不喜欢那样,因为它们依赖于这样一个事实,即跟踪 GC 可能不会在对象不再被强引用后立即收集它,除非在内存不足的情况下.这些类型的情况对于引用计数 GC 是绝对无效的,因为对象在不再被引用后立即被销毁(除非可能在循环的情况下).

I figure that there must be some reason they exist, especially in languages with tracing garbage collection, which do not suffer from the cyclic reference pitfall (C# and Java are the ones I'm familiar with, and Java even has three kinds of weak references!). When I've tried to find some solid use-cases for them, though, I pretty much just got ideas like "Use them to implement caches" (I've seen that a few times on SO). I don't like that either, since they rely on the fact that a tracing GC will likely not collect an object immediately after it's no longer strongly referenced, except in low-memory situations. These kinds of cases are absolutely invalid with reference counting GC since an object is destroyed immediately after it is no longer referenced (except possibly in the case of cycles).

但这真的让我想知道:弱引用怎么可能有用?如果你不能指望它引用一个对象,而且它不需要像打破循环这样的事情,那为什么要使用一个?

But that really leaves me wondering: How can a weak reference possibly be useful? If you can't count on it referencing an object, and its not needed for things like breaking cycles, then why use one?

推荐答案

事件处理程序是弱引用的一个很好的用例.触发事件的对象需要对对象的引用以调用事件处理程序,但您通常不希望事件生产者的引用保持以防止事件使用者被 GC 处理.相反,您希望事件生产者有一个弱引用,然后它负责检查被引用的对象是否仍然存在.

Event handlers are a good use case for weak references. The object that fires events needs a reference to the objects to invoke event handlers on, but you typically don't want the event producer's reference holding to prevent the event consumers from being GC'd. Rather, you'd want the event producer to have a weak reference, and it would then be responsible for checking whether the referenced object was still present.

这篇关于弱引用 - 它们有多有用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 19:18