A Refcounted Array Type

Steven Schveighoffer via Digitalmars-d digitalmars-d at puremagic.com
Tue Feb 24 06:56:12 PST 2015


On 2/24/15 8: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.
>

Actually, RCArray can never be allocated on GC, or you may corrupt 
memory. count may be non-null, and point at invalid memory when the dtor 
is called.

Only safe way to do this is to C malloc/free the count. And yes, at that 
point, you need atomics.

-Steve


More information about the Digitalmars-d mailing list