Why are immutable array literals heap allocated?

Nick Treleaven nick at geany.org
Sat Jul 6 10:53:39 UTC 2019


On Friday, 5 July 2019 at 23:05:32 UTC, Jonathan M Davis wrote:
>> Yes, I was wondering why the compiler doesn't statically 
>> allocate it automatically as an optimization.
>
> It would have to be set up to store the literal somewhere else.

I was thinking the read-only data segment.

> Certainly, it can't just put it on the stack, because that 
> risks it going out of scope and causing memory problems. It

It can do that with small-ish sized literals if they don't escape 
(-dip1000). I think Walter may have advocated something like 
this. This one can be done even with literals of mutable elements.

> no matter what optimizations the compiler does with array 
> literals, that shouldn't affect whether the function can be 
> @nogc. For it to affect that, it would have to be something 
> that was guaranteed by the language's semantics regardless of 
> whether any optimizations were being done.

Yes, just like string literals I think static allocation can be 
part of the language for immutable data.



More information about the Digitalmars-d-learn mailing list