c++iteratorinput-iterator

Crafting an InputIterator that does not store the value_type


I am creating a type that models InputIterator. In my application, "skip the first hundred thousand elements" is a reasonable thing to do, and creating the value_type is expensive, so I want my iterator to create the value_type only when dereferenced, not when incremented.

I could easily make operator* return the value_type by value. But I do not know what to do about operator->. How can I return a pointer if my iterator is not storing the value_type? I'm afraid of lifetime problems with a pointer-to-temporary, and don't want to get burned.

I have thought about not providing operator->, but then I wouldn't have a complete InputIterator.


Solution

  • I believe it will work to return a proxy object by value from the iterator's operator->. The proxy would have a single value_type data member, and its own operator-> returning a pointer to that data member.

    The lifetime of the proxy object is the same as any other return by value object (like my plan for operator*), so although I do have a pointer-to-temporary, in these circumstances it is consumed before the proxy object is destroyed.