Why char[] is not @nogc on this case
Jonathan M Davis
newsgroup.d at jmdavisprog.com
Fri May 25 00:07:20 UTC 2018
On Thursday, May 24, 2018 23:55:24 SrMordred via Digitalmars-d-learn wrote:
> int[] a;
> int[] b;
>
> ()@nogc {
> foreach(v ; chain( a,b ) ) printf("%d\n", v);
> }();
>
> //Ok, everything fine;
>
> char[] a;
> char[] b;
>
> ()@nogc {
> foreach(v ; chain( a,b ) ) printf("%c\n", v);
> }();
>
> //Error: @nogc delegate onlineapp.main.__lambda1 cannot call
> non- at nogc function std.range.chain!(char[],
> char[]).chain.Result.front
>
> Why?
Because arrays of char and wchar are treated as ranges of dchar.
std.primitives.range.front and popFront call std.utf.decode and stride
respectively so that front returns dchar. decode (and possibly stride - I'd
have to check) throw a UTFException on invalid Unicode, and that means that
they allocate with the GC. If you want to avoid the auto-decoding, you have
to use something like std.string.representation or std.utf.byCodeUnit to
wrap the array of chars before passing them to any range-based functions.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list