Do array literals still always allocate?

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon May 15 06:37:30 PDT 2017


On 5/14/17 7:40 AM, Nicholas Wilson wrote:
> On Sunday, 14 May 2017 at 10:18:40 UTC, ag0aep6g wrote:
>> On 05/14/2017 01:57 AM, Nicholas Wilson wrote:
>>> 1D arrays it doesn't, 2D or higher it does.
>>
>> What do you mean? This works just fine as well:
>>
>> ----
>> import std.random;
>> import std.stdio;
>>
>> int[2][2] testfunc(int num) @nogc
>> {
>>     return [[0, 1], [num, 3]];
>> }
>>
>> int main()
>> {
>>     int[2][2] arr = testfunc(uniform(0, 15));
>>     writeln(arr);
>>     return 0;
>> }
>> ----
>
> dynamic array literals is what I meant.

dynamic array literals allocate most of the time. The one time they 
don't is the specialized case of initializing a static array, I think of 
any dimension.

However, to the OP's point, they *did* allocate up until a certain 
version, even when initializing a static array.

That is:

int[2] x = [1, 2];

used to allocate a dynamic array on the heap, and then copy the data 
into x (and leave the allocated data for the GC). Now it just populates 
x without allocating.

LDC might be smarter, and take more valid shortcuts, so that is good. 
But in general you can expect array literals to allocate when not used 
as static array initializers.

-Steve


More information about the Digitalmars-d-learn mailing list