question about passing associative array to a function

ed via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun May 11 19:04:27 PDT 2014


On Sunday, 11 May 2014 at 14:46:35 UTC, 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 AA is passed by value but its underlying data is referenced, 
making the copy cheap. The snippet below also shows the same 
behaviour even when the AA has data in it before calling the 
function.
---
void func(string[int] aa)
{
     writefln("[FUNC1]    &aa:%s=%s", &aa, aa);

     // Reassign the data here in func()'s copy and
     // main never sees it
     aa = [2:"two"];
     writefln("[FUNC2]    &aa:%s=%s", &aa, aa);

}

void main()
{
     string[int] aa;
     aa[1] = "one";
     writefln("[MAIN1]    &aa:%s=%s", &aa, aa);
     func(aa);
     writefln("[MAIN2]    &aa:%s=%s", &aa, aa);

}
---

It is the same as passing a C++ shared_ptr<> by value.

Cheers,
ed


More information about the Digitalmars-d-learn mailing list