Why are immutable array literals heap allocated?
Patrick Schluter
Patrick.Schluter at bbox.fr
Fri Jul 5 23:08:04 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]?
int[] in D is not an array but a fat pointer. When one realizes
that then it become quite obvious why [1,2] was allocated. There
is somewhere in the binary a static array [1,2] but as it is
assigned to a pointer to mutable data, the compiler has no choice
as to allocate a mutable copy of that immutable array.
More information about the Digitalmars-d-learn
mailing list