Foreach/opApply with @nogc

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Aug 24 11:45:14 PDT 2014


On 08/24/2014 06:40 AM, ketmar via Digitalmars-d-learn wrote:

 > On Sun, 24 Aug 2014 13:22:49 +0000
 > Stefan Frijters via Digitalmars-d-learn
 > <digitalmars-d-learn at puremagic.com> wrote:
 >
 > @nogc is a part of signature. gc-function can't call @nogc-one. the
 > same is with calling @system function from @safe one, for example. or
 > impure function from pure.
 >
 > so to say, foreach() creates implicit delegate withoit '@nogc'
 > attribute, that's why compiler complains.
 >
 > there is currenly no way to specify attributes for such implicit
 > delegates. this will work, but you'll not be able to call writeln():
 >
 >    nogc:
 >    void main() {
 >       import std.stdio;
 >       foreach (element; NumberRange(3, 7)) { // line 21
 >         //write(element, ' '); // this will fail with
 >           // @nogc function 'z00.main.__foreachbody1' cannot call
 >           // non- at nogc function 'std.stdio.write!(int, char).write'
 >      }
 >    }

Yeah, the only reason why the original code does not work is the write() 
expression in the foreach body. If I am not mistaken, the attributes are 
inferred for templates and delegates; the foreach body becomes @nogc if 
it can be @nogc.

 > what we need here is something like:
 >
 >    foreach (element; NumberRange(3, 7) @nogc) { ... }
 >
 > but alas...

I have discovered that the following works but of course it is not the same:

   @nogc range = NumberRange(3, 7);
   foreach (element; range) {
     // write(element, ' ');
   }

Ali



More information about the Digitalmars-d-learn mailing list