auto f() { return "abc"; } // @nogc, cheap
auto g() { return ['a', 'b', 'c']; } // allocates via GC, at runtime
Comment #1 by eyal — 2021-03-24T09:10:03Z
I am lacking a way to say the array literal is immutable, so it gets allocated the same way a string literal does.
This is especially problematic in a function like:
@nogc string f() {
enum compileTimeStr = "fmt %x".format(someNum());
return compileTimeStr; // GC allocation here
}
Comment #2 by b2.temp — 2021-03-31T18:23:45Z
cast(immutable) could do that. Under the hood a hidden static immutable would be created.
Comment #3 by dlang-bot — 2021-03-31T18:24:48Z
@TungstenHeart created dlang/dmd pull request #12329 "fix 21756 - make `cast(immutable)arrayLiteral` @nogc" fixing this issue:
- fix 21756 - make `cast(immutable)arrayLiteral` @nogc
adjust array literal semantics so that
```d
cast(immutable) <arrayLiteral>
```
gets rewritten to a DeclExp comma VarExp
```d
(static immutable __array = <arrayLiteral>, __array)
```
allowing immutable array literals to be `@nogc`
https://github.com/dlang/dmd/pull/12329
Comment #4 by pro.mathias.lang — 2021-04-01T00:10:12Z
No, `cast` should not do this magic, it should be requested by the user directly.
So:
```
auto g() { static immutable ret = ['a', 'b', 'c']; return ret; }
```
Leaving open for the benefit of the discussion (I found this issue because there's a PR), but IMO this is RESOLVED INVALID territory.
Comment #5 by eyal — 2021-04-01T20:14:38Z
Neither the PR nor this solution seem to resolve the issue. Consider these pieces of code.
Will NOT compile:
@nogc string f() {
static immutable s = "%5d".format(5);
enum u = s;
return u; // does GC :-(
}
Will compile fine:
@nogc string f() {
static immutable s = "%5d".format(5);
enum u = s ~ "";
return u; // all is well
}
Will also compile fine:
@nogc string f() {
static immutable s = "%5d".format(5) ~ "";
enum u = s;
return u; // all is well
}
Surely this cannot be considered a reasonable state of things?
Comment #6 by robert.schadek — 2024-12-13T19:15:24Z