How come a count of a range becomes 0 before a foreach?
Steven Schveighoffer
schveiguy at gmail.com
Tue Apr 11 01:55:39 UTC 2023
On 4/10/23 6:43 PM, ikelaiah wrote:
> On Monday, 10 April 2023 at 01:01:59 UTC, Steven Schveighoffer wrote:
>> On 4/9/23 9:16 AM, Ali Çehreli wrote:
>>> auto entries = dirEntries(/* ... */).array;
>>
>> I'd be cautious of that. I don't know what the underlying code uses,
>> it may reuse buffers for e.g. filenames to avoid allocation.
>>
>> If you are confident the directory contents won't change in that
>> split-second, then I think iterating twice is fine.
>>
>
> Steve,
>
> The Rmd files are not on a network drive, but saved locally.
> So, I'm confident, the files won't change in a split-second.
That is not what I meant.
What I mean is that `array` is going to copy whatever values the range
gives it, which might be later *overwritten* depending on how
`dirEntries` is implemented.
e.g. the following code is broken:
```d
auto lines = File("foo.txt").byLine.array;
```
But the following is correct:
```
auto lines = File("foo.txt").byLineCopy.array;
```
Why? Because `byLine` reuses the line buffer eventually to save on
allocations. The array of lines might contain garbage in the earlier
elements as they got overwritten.
I'm not saying it's wrong for `dirEntries`, I haven't looked. But you
may want to be cautious about just using `array` to get you out of
trouble, especially for lazy input ranges.
-Steve
More information about the Digitalmars-d-learn
mailing list