Is there a weak pointer or references in D?
Alex Rønne Petersen
alex at lycus.org
Sun Jan 13 21:01:21 PST 2013
On 14-01-2013 00:18, Charles Hixson wrote:
> On 01/12/2013 09:24 PM, Alex Rønne Petersen wrote:
>> On 11-01-2013 19:15, Charles Hixson wrote:
>>> I was looking for a way to create a weak reference to either a struct or
>>> a class. I need to be able to use it to automatically generate an
>>> active reference on access. (I intend to do this by rolling in data
>>> from a file.)
>>>
>>> Any guidance as to where I should look?
>>
>> https://github.com/lycus/mci/blob/master/src/mci/core/weak.d
>>
>> It has some caveats (see the comments).
>>
>
> It certainly does have some caveats. And according to at least one of
> them it may break badly in the future from a plausible compiler change.
>
> Well, it's what I asked for, but using something that can be expected to
> break without warning. I want to write code that I can forget after I
> test.
>
> It would have been a great convenience, but that's a bit too high a
> price to pay for a convenience.
>
Well, I'm not going to lie: You cannot implement weak references in D
any other way. The GC just isn't helpful enough.
The only way this code could break is if D ever gets a copying or
compacting GC. The chances of that happening, ever, are practically nil
because such GCs are extremely impractical in natively-compiled systems
languages.
Otherwise all you have to be aware of in your code is that the
referenced object cannot be used as a mutex in synchronized statements
and cannot have custom dispose events (finalizers).
(Note, the last part there doesn't mean that the referenced object can't
have a finalizer declared via `~this()` - it just means that you should
not dynamically attach finalizers to it with rt_attachDisposeEvent().)
--
Alex Rønne Petersen
alex at alexrp.com / alex at lycus.org
http://lycus.org
More information about the Digitalmars-d-learn
mailing list