A Refcounted Array Type

Andrei Alexandrescu via Digitalmars-d digitalmars-d at puremagic.com
Tue Feb 24 08:29:41 PST 2015


On 2/24/15 5:17 AM, Michel Fortin wrote:
> On 2015-02-23 22:15:46 +0000, Walter Bright said:
>
>> int* count;
>>
>> [...] if (count && --*count == 0) [...]
>
> Careful!
>
> This isn't memory safe and you have to thank the GC for it. If you ever
> use RCArray as a member variable in a class, the RCArray destructor is
> going to be called from a random thread when the class destructor is
> run. If some thread has a stack reference to the array you have a race.
>
> You have to use an atomic counter unless you can prove the RCArray
> struct will never be put in a GC-managed context. It is rather sad that
> the language has no way to enforce such a restriction, and also that
> @safe cannot detect that this is a problem here.

Good point. This is already a danger in existing code, e.g. File uses 
reference counting. I just submitted 
https://issues.dlang.org/show_bug.cgi?id=14221.

Andrei




More information about the Digitalmars-d mailing list