For most lists it is easy to create an enumerator, but lately I was thinking, it would be nice to have an enumerator for a lazy list that calculates the values while enumerating.
This leads to the problem, after the value has been calculated and the enumerator is done, how can you free that value?
I do not want to have the enumerator on the heap, because that is unnecessary slow, so it cannot be a class-based enumerator with destructor.
The record-based enumerator does not have a destructor, so it cannot free the value.
You cannot put a guard interface in the record, because that is even slower.
You cannot free it on movenext returning false, because the loop might be broken.
You cannot precalculate all the values, when the enumerator is created, because that would not be lazily and there would be no point in this anymore.
You cannot store the currently calculated value in the list, because that is not thread-safe, and also, because you won't know when the enumerator is done.
You cannot keep the enumerator in the lazy list and return an instance of it, because that is not thread safe, either, and you cannot have nested enumerators
So how could it be done?