foreach without front
Jonathan Marler via Digitalmars-d
digitalmars-d at puremagic.com
Mon Aug 11 13:09:49 PDT 2014
> `foreach` should manage it's own iterator's resources - it
> shouldn't rely on some memory declared outside it's scope
> that'll be accessible after the loop is finished. You can
You say `foreach` should manage it's own iterator's resources but
why? The std.stdio function byChunk allows you to pass in a slice
to a buffer to memory that is managed outside the iterators
resources. Passing in memory-pointers to iterators is necessary
for memory optimization in some cases.
> always manage the iteration manually:
>
> struct MyData {
> int someInt;
> string someString;
> ubyte[128] data;
> }
>
> struct MyDataInputRange {
> MyData* dataBuffer;
> this(MyData* dataBuffer) {
> this.dataBuffer = dataBuffer;
> }
> bool moveNext() { /* return true unless reached the end
> of the loop */ }
> }
> void main()
> {
> MyData data;
> for(auto dataInputRange = MyDataInputRange(&data);
> dataInputRange.moveNext();) {
> }
> }
Yes managing the array manually is an obvious solution but like I
said I'm just being "nit picky". I am exposing this class in a
library and would like to encourage others to use it in the
optimal way which would be to omit the call to the front function
and just access the struct directly.
I also thought of another case where this would be useful:
foreach(0..count) {
// do something count number of times where
// you don't need the current count
}
Again I don't see this being needed very often it would just be
nice syntax sugar that I don't anticipate would be very hard to
implement:)
More information about the Digitalmars-d
mailing list