weak references

Bill Baxter wbaxter at gmail.com
Wed Aug 6 05:50:43 PDT 2008


On Wed, Aug 6, 2008 at 9:13 PM, PJP <pete.poulos at gmail.com> wrote:
> I don't think this solution is safe.  According to (http://www.digitalmars.com/d/2.0/garbage.html), this is undefined behavior, "Do not store pointers into non-pointer variables using casts and other tricks. "

This one is I think just trying to warn you that your pointer stored
in a non-pointer variable may likely be collected out from underneath
you.  But that's exactly what you want out of a weak reference.

> and "Do not store into pointers values that may point into the garbage collected heap...A copying garbage collector may change this value"

That one is more troublesome, but a) D is not likely to get a copying
collector any time soon.  b) using a WeakRef class now for all your
weak reference needs should make it easy to upgrade all your code.
Just replace WeakRef's implementation with the built in thing.  c)
It's all there is for now, as far as I know.  d) std.signals relies on
the same trick.

That said, I kind of wrote it just because it seemed like it should
work, and it was needed.  But I wasn't really sure if it would work
(or even if it works properly now -- it's quite hard to test because
the GC has no diagnostics to tell you about what outstanding
references it thinks exist).   So I was half expecting someone to say
"no no no that's not how you write a weak ref in D, /here's/ how you
do it", and then the plan was that I would use that one too.  :-)
But no such person stepped out of the woodwork.

--bb

>
> PJP
>
> Bill Baxter Wrote:
>
>> It provides a call-back hook that can be set to get a notification
>> when an object you're interested in is destroyed.
>> And in general size_t's and other integer types are not treated as pointers.
>>
>> These two things can be used to make a weak ref class, which is what
>> has been done here:
>>
>> http://www.dsource.org/projects/scrapple/browser/trunk/weakref
>>
>> On Wed, Aug 6, 2008 at 2:06 PM, PJP <pete.poulos at gmail.com> wrote:
>> >
>> > Does the D garbage collector provide something similar to the "weak" references in Java?  Weak references don't prevent the object they refer to from being garbage collected.  If the object has been garbage collected, the weak reference will return null.
>> >
>
>


More information about the Digitalmars-d-learn mailing list