Why are immutable array literals heap allocated?

Eugene Wissner belka at caraus.de
Thu Jul 4 11:06:36 UTC 2019


On Thursday, 4 July 2019 at 10:56:50 UTC, Nick Treleaven wrote:
> immutable(int[]) f() @nogc {
>     return [1,2];
> }
>
> onlineapp.d(2): Error: array literal in `@nogc` function 
> `onlineapp.f` may cause a GC allocation
>
> This makes dynamic array literals unusable with @nogc, and adds 
> to GC pressure for no reason. What code would break if dmd used 
> only static data for [1,2]?

immutable(int[]) f() @nogc {
     static immutable arr = [1, 2];
     return arr;
}

You have to spell it out that the data is static.


More information about the Digitalmars-d-learn mailing list