auto arr = [1, 2, 3] should be a static array, not a GC allocated array
Quirin Schroll
qs.il.paperinik at gmail.com
Tue Jul 19 14:04:09 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]
> ```
>
> Also why it is GC allocated without requiring ``new``?
Because it’s useful to more people than if it were the opposite.
If you find that `staticArray` too verbose, there’s a
single-keystroke way to get pseudo-literals for static arrays:
```D
struct s
{
static typeof([ Ts.init ][0])[Ts.length] opIndex(Ts...)(auto
ref Ts args)
{
import std.functional : forward;
return [ forward!args ];
}
}
```
Usage:
```D
void main()
{
auto empty = s[];
static assert(is(typeof(empty) == void[0]));
auto xs = s[1,cast(byte)2,3];
static assert(is(typeof(xs) == int[3]));
static struct NoCopy { @disable this(this); }
auto noCopies = s[NoCopy(), NoCopy()];
}
```
You’re free to choose any name (except keywords). If you name it
`stackalloc`, it almost looks like taken from C#.
More information about the Digitalmars-d
mailing list