Associative array on the heap

mw mingwu at gmail.com
Tue Jul 7 07:08:46 UTC 2020


On Tuesday, 19 May 2015 at 12:21:48 UTC, Steven Schveighoffer 
wrote:
> On 5/18/15 7:55 PM, Freddy wrote:
>> How do you allocate an associative array on the heap?
>> ----
>> void main(){
>>      alias A=int[string];
>>      auto b=new A;
>> }
>> ----
>> $ rdmd test
>> test.d(4): Error: new can only create structs, dynamic arrays 
>> or class
>> objects, not int[string]'s
>> Failed: ["dmd", "-v", "-o-", "test.d", "-I."]
>
> As others have said, I don't know why you would want to do 
> this, since AA is already simply a wrapper for a pointer to a

AA is a wrapper for a pointer (e.g a struct with some extra info 
beyond the plain pointer), or AA is just the plain pointer 
(nothing extra)?

I tried this:

   class Foo {}
   Foo[string] foos;
   writeln(foos.sizeof);  // print 8

looks like it's just a plain pointer?


The usage pattern to have AA on the heap is, e.g:

class Class {
   StudentInfo[string] students;  // dict-by-name
   // many other fields
}

suppose in a multi-threaded app, the Class object is shared, and 
one thread will perform a lengthy updates on all the students. To 
ensure data consistency among all the students object, instead of 
updating each student's info of the original AA in a loop (with 
lengthy locking period), it can be achieved by heap-alloc a new 
AA, update the new AA, and atomic-set:

   new_students = new StudentInfo[string];  // heap-alloc a new AA
   // length update on each of new_students
   atomicStore(theClass.students, new_students);




More information about the Digitalmars-d-learn mailing list