On 8/24/21 1:44 PM, Ferhat Kurtulmuş wrote:

> Just out of curiosity, if a range implementation uses malloc in save, is
> it only possible to free the memory with the dtor?

Yes but It depends on the specific case. For example, if the type has a clear() function that does clean up, then one might call that. I don't see it as being different from any other resource management.

> Is a save function only meaningful for GC ranges?

save() is to store the iteration state of a range. It should seldom require memory allocation unless we're dealing with e.g. stdin where we would have to store input lines just to support save(). It would not be a good design to hide such potentilly expensive storage of lines behind save().

To me, save() should mostly be as trivial as returning a copy of the struct object to preserve the state of the original range. Here is a trivial generator:

import std.range;

struct Squares {
  int current;

  enum empty = false;

  int front() const {
    return current * current;
  }

  void popFront() {
    ++current;
  }

  auto save() {
    return this;
  }
}

void main() {
  auto r = Squares(0);
  r.popFront();  // Drop 0 * 0
  r.popFront();  // Drop 1 * 1

  auto copy = r.save;
  copy.popFront();  // Drop 2 * 2 only from the copy

  assert(r.front == 2 * 2);  // Saved original still has 2 * 2
}

Ali


Reply via email to