Associative Array c'tor

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Jul 11 07:53:22 PDT 2016


On 7/11/16 10:33 AM, Bahman Movaqar wrote:
> On 07/11/2016 06:30 PM, Steven Schveighoffer wrote:
>> But passing empty AA by value sometimes can be surprising. I'm not sure
>> if it will work.
>
> Could you elaborate more?

An AA initializes on demand. So if you pass by value *after* it has been 
initialized it behaves like a reference type. But before it's 
initialized, it's essentially a null pointer. This can cause surprising 
behavior:

foo(int[int] aa)
{
     foreach(i; 0 .. 100)
         aa[i] = i;
}

void main()
{
     import std.random;
     int[int] aa; // initialized as null
     if(uniform!ubyte < 128)
         aa[0] = 0; // intialized
     foo(aa);

     // at this point, depending on random initialization, either aa is 
filled or is still null.
}

-Steve


More information about the Digitalmars-d-learn mailing list