question about passing associative array to a function

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun May 11 10:11:55 PDT 2014


On 05/11/2014 10:00 AM, John Colvin wrote:
 > On Sunday, 11 May 2014 at 16:54:18 UTC, Ali Çehreli wrote:
 >> On 05/11/2014 07:46 AM, rbutler wrote:
 >>
 >> > I have searched and can not understand something about
 >> passing AAs to a
 >> > function.
 >> > I have reduced the gist of the question to a tiny program
 >> below.
 >> > If I put "ref"  in the function stmt it works, i.e.:
 >> >          ref int[int] aa
 >> > My confusion is that AAs are supposed to be passed as refs
 >> anyway, so I do
 >> > not understand why I should have to use ref to make it work.
 >> >
 >> > Related, it also works if I UN-comment the line    d[9] = 9;
 >> >
 >> > Thanks for any helpful comments you can make.
 >> > --rbutler
 >> >
 >> > import std.stdio;
 >> >
 >> > void test(int[int] aa, int x) {
 >> >      aa[x] = x;
 >> >      aa[8] = 8;
 >> > }
 >> >
 >> > void main() {
 >> >      int[int] d;
 >> >      writeln(d.length);
 >> >      // d[9] = 9;
 >> >      test(d, 0);
 >> >      writeln(d);
 >> > }
 >>
 >> The problem is with the initial state of associative arrays, which
 >> happens to be null. When AAs are copied when null, both copies are
 >> null, not being associated with anything, not even an initial table to
 >> store the hash buckets in. As a result, null AAs cannot be references
 >> to each other's (non existent) data.
 >>
 >> When a null AA starts receiving data, it first creates its own data
 >> memory but the other one cannot know about that data.
 >>
 >> ref parameter works because then there is only one AA to speak of.
 >>
 >> d[9] entry works as well because then the first AA is not null.
 >>
 >> Ali
 >
 > Remind me again why we can't just change this to a sensible initial
 > state?

First, I am not familiar with the current implementation of AAs and I 
deduced what I've written just from the behavior.

I think it is this way primarily for lazy initialization so that nothing 
is done until there is at least one element. It could still work as 
expected though if there were another level of indirection, which would 
naturally add some cost. (Although, lazy initialization brings a 
constant cost as well, right? In the form of "has this been initialized 
yet"; but that cost is as cheap as checking the value of a local 
variable. On the other hand, an indirection would be cache-unfriendly. 
And this is pure speculation... :p)

 > Or at least add a .initialize()?

Your initAA() function seems to be the only way that a user can manage 
to do that. Although, it would help if we renamed it as initialize() and 
added a template constraint so that it is called only for AAs.

Ali



More information about the Digitalmars-d-learn mailing list