In D, all array literals are dynamic arrays, and are therefore allocated by the GC.
Even in this simple example:
int[3] a = [10, 20, 30];
The array is heap-allocated and then copied into a
.
How are you supposed to initialise a static array without heap-allocation?
You could do it manually:
int[3] a = void;
a[0] = 10;
a[1] = 20;
a[2] = 30;
But this is tedious at best.
Is there a better way?
2017 UPDATE: In any recent version of DMD, using an array initializer on a static array no longer allocates, even if the static array is a local variable (ie stack-allocated).
You can verify this yourself by creating a function where a static array is initialized, and then marking the function as @nogc and observing whether or not it compiles. Example:
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;
}
Since testfunc() compiles despite being @nogc, we know that the array initializer does not allocate.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With