auto arr = [1, 2, 3] should be a static array, not a GC allocated array

Dukc ajieskola at gmail.com
Sat Jul 16 16:27:06 UTC 2022


On Thursday, 14 July 2022 at 13:14:59 UTC, ryuukk_ wrote:
> It is misleading, nobody expect this to be GC allocated
>
> It should be equal to:
>
> ```D
> int[3] arr = [1, 2, 3]
> ```
>

TDPL book deals with this question. Andrei said that "experience 
with pascal" shows it's better to be dynamic by default.

> Also why it is GC allocated without requiring ``new``?

Otherwise it would have to be either immutable or impure. 
Consider:

```D
@safe pure int[] fun()
{ auto arr = [1, 2, 3];
   return arr;
}

@safe void main()
{ import std.stdio;
   auto arr1 = fun();
   foreach(ref el; arr1) el += 3;
   auto arr2 = fun();
   foreach(ref el; arr2) el += 10;
   arr1.writeln;
   arr2.writeln;
}
```

GC allocation is the only way this can work. If `arr` was 
allocated from static data, the two calls to `fun` would refer to 
the same array, meaning the output would be
```
[11, 12, 13]
[11, 12, 13]
```
. `fun` would not be pure at all!

`arr` in `fun` also can not be stack allocated, because stack 
allocations can last only until the function that allocated 
returns. `arr` is returned, meaning it needs to continue existing 
beyond returning from `fun`.




More information about the Digitalmars-d mailing list