Do array literals still always allocate?

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat May 13 12:22:09 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. However, testfunc() above compiles as 
> @nogc. This would indicate to me that D does the smart thing 
> and avoids a heap allocation for an array literal being used to 
> populate a static array. Is all the old stuff I was reading 
> just out-of-date now?

It's just out of date. Can't remember the version, but this did 
use to allocate. It doesn't any more. But only for this case. In 
most cases it does allocate.

-Steve



More information about the Digitalmars-d-learn mailing list