You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
DMD 2.066alpha accepts this code:
// Program#1
void main() @nogc {
int[2] tmp = [1, 2];
foreach (x; tmp) {}
}
While it refuses this code:
// Program#2
void main() @nogc {
foreach (x; [1, 2]) {}
}
With:
test.d(3,17): Error: array literal in @nogc function main may cause GC allocation
I suggest to start introducing a small amount of Escape Analysis in D, to support the @nogc attribute for the Program#2.
Eventually even this program could be supported:
// Program#3
void main() @nogc {
import std.algorithm: filter;
foreach (x; [1, 2].filter!(x => true)) {}
}
Note that with the []s suffix syntax for fixed-size arrays there is no ambiguity:
// Program#4
void main() @nogc {
foreach (x; [1, 2]s) {}
}
And this can generate a clean error message (escape of pointer to stack frame fixed-size array):
// Program#5
int[] foo() @nogc {
return [1, 2]s;
}
void main() {}
See also Issue 10242
The text was updated successfully, but these errors were encountered:
stanislav.blinov commented on 2021-12-08T16:23:42Z
Rewritten relevant parts into contemprary D. With dmd 2.098:
void program2() @nogc {
foreach (x; [1, 2]) {}
}
import std.array : staticArray;
void program3() @nogc {
import std.algorithm: filter;
foreach (x; [1, 2].filter!(x => true)) {} // fails to infer @nogc
// workaround:
foreach (x; [1, 2].staticArray[].filter!(x => true)) {}
}
int[] program5() @nogc {
return [1, 2].staticArray; // detects the escape correctly
}
void main() {}
So I guess the only outstanding enhancement here is to make this infer @nogc:
foreach (x; [1, 2].filter!(x => true)) {}
...if at all possible. If not, I guess this could be closed?
bearophile_hugs reported this on 2014-05-26T21:53:34Z
Transferred from https://issues.dlang.org/show_bug.cgi?id=12808
CC List
Description
The text was updated successfully, but these errors were encountered: