Weak references.

Bill Baxter dnewsgroup at billbaxter.com
Sat Apr 12 16:50:52 PDT 2008


Jarrett Billingsley wrote:
> I've been looking at some of my old nonagon code, and as I'm sure you've all 
> experienced looking at your old code, I'm just _cringing_ at some of the 
> things I did in it ;)
> 
> One thing that I've noticed would be nice to have, however, would be weak 
> references to some objects.  For example, I have "brush" objects which 
> encapsulate a bunch of visual settings (textures, material, blending modes 
> etc.).  These are referenced by objects that can be rendered.  Some of these 
> brushes need to be updated often (i.e. every frame to update the environment 
> mapping matrices).  So I keep a list (table) of all instances of this brush 
> class so I can easily loop through them and update them all.
> 
> However when their owners disappear, I end up with uncollectable brushes, 
> since they are still being referenced by that table.
> 
> So what would be nice to have happen would be to have that table be a table 
> of _weak references_ to brush objects.  Then, when no more real references 
> existed, they could be collected, and I wouldn't be keeping them around for 
> no reason anymore.
> 
> I've looked into the scrapple weakref implementation, but it doesn't seem to 
> do what I want.  Seemingly it only works if the object that it references is 
> explicitly deleted.  I want the weakref to become null if the object that it 
> references is collected in any way.
> 
> Is this possible at all?  Am I just not using Bill's weakref properly? 
> 
> 

It does exactly what you're asking for ... as long as your "Brushes" are 
class instances, which it sounds like they are.
Instead of filling the table with type Brush, fill it with type 
WeakRef!(Brush).  Then when you go to use them from the table you should 
check for null first.  If the ptr value is null, it means the object got 
collected at some point, so you can remove it from the table.

--bb



More information about the Digitalmars-d mailing list