Is there a weak pointer or references in D?

Jonathan M Davis jmdavisProg at gmx.com
Fri Jan 11 18:49:18 PST 2013


On Saturday, January 12, 2013 00:51:02 Nekroze wrote:
> On Friday, 11 January 2013 at 22:07:45 UTC, monarch_dodra wrote:
> > Honest question: How can you have a weak pointer in a language
> > that is garbage collected?
> 
> I beleive the OP means something like pythons weakref
> (http://docs.python.org/2/library/weakref.html) that is qoute:
> 
> A weak reference to an object is not enough to keep the object
> alive: when the only remaining references to a referent are weak
> references, garbage collection is free to destroy the referent
> and reuse its memory for something else.
> 
> I would like to have no how to do something like this in D aswell
> as it could be handy.

That doesn't fly with the GC, because then you can have a reference to memory 
that's been freed - though I suppose that it could work if the weak reference 
were set to null when the normal reference was collected.

There's no reason that you couldn't do that with ref-counted objects, so 
perhaps something like that could be done with std.typecons.RefCounted, but we 
don't currently have anything like that, and you'd still need to make the weak 
ref null when the normal ref is destroyed, or you'd have memory safety issues.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list