new int[]

Jonathan M Davis newsgroup.d at jmdavisprog.com
Wed Jan 10 23:11:22 UTC 2018


On Wednesday, January 10, 2018 22:50:22 Nathan S. via Digitalmars-d-learn 
wrote:
> On Wednesday, 10 January 2018 at 22:46:30 UTC, ag0aep6g wrote:
> > If I understand correctly, the goal is to have the `int[]`
> > itself on the GC heap.
>
> The code
> ----
> void main(string[] args) @nogc
> {
>      int[] x = [1, 2, 3];
> }
> ----
>
> won't compile, because "array literal in @nogc function 'D main'
> may cause GC allocation". But "may" isn't the same as "will".
> What determines it? That's a kind of goofy error message now that
> I think about it.

If there are cases where it doesn't allocate, it probably depends on
compiler optimizations. If it's able to determine that x doesn't escape the
function, it might allocate it on the stack. I don't know. But @nogc is
about guaranteeing that it _won't_ allocate using the GC, so "may" is enough
to make it illegal for @nogc. It's also possible that this particular case
will always allocate, but the error message is also used in other code where
it's not guaranteed to allocate. Recently, in a discussion on improving
error messages Walter did mention that there are cases in the compiler where
the same piece of code generates errors for a variety of cases and that it
would probably be better to make some of those less generic so that the
error messages can be more specific.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list