Do array literals still always allocate?

Stanislav Blinov via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat May 13 12:04:22 PDT 2017


On Saturday, 13 May 2017 at 18:32:16 UTC, Lewis wrote:
> import std.random;
> import std.stdio;
>
> int[4] testfunc(int num) @nogc
> {
>     return [0, 1, num, 3];
> }
>
> int main()
> {
>     int[4] arr = testfunc(uniform(0, 15));
>     writeln(arr);
>     return 0;
> }
>
> I've read a bunch of stuff that seems to indicate that array 
> literals are always heap-allocated, even when being used to 
> populate a static array.

On the contrary, when initializing static arrays, allocation is 
not needed.
Note that what's *conceptually* happening in testfunc is this:

>int[4] testfunc(int num) @nogc
>{
>    typeof(return) result = [0, 1, num, 3];
>    return result;
>}

i.e. the type and size of the storage is known beforehand, all 
there is to do is copy the elements:

000000000044e528 <@nogc int[4] test.testfunc(int)>:
   44e528:       55                      push   %rbp
   44e529:       48 8b ec                mov    %rsp,%rbp
   44e52c:       48 83 ec 10             sub    $0x10,%rsp
   44e530:       48 89 7d f8             mov    %rdi,-0x8(%rbp)
   44e534:       c7 07 00 00 00 00       movl   $0x0,(%rdi)      # 
0 goes at offset 0
   44e53a:       c7 47 04 01 00 00 00    movl   $0x1,0x4(%rdi)   # 
1 at offset 4
   44e541:       89 77 08                mov    %esi,0x8(%rdi)   # 
parameter at offset 8
   44e544:       c7 47 0c 03 00 00 00    movl   $0x3,0xc(%rdi)   # 
3 at offset 12
   44e54b:       48 8b 45 f8             mov    -0x8(%rbp),%rax
   44e54f:       c9                      leaveq
   44e550:       c3                      retq

> Is all the old stuff I was reading just out-of-date now?

Where exactly did you read that initialization of a static array 
requires an allocation? That source should be abolished... 
errrm... corrected!


More information about the Digitalmars-d-learn mailing list