1

I am implementing a custom input iterator. It does not store the current value in a member variable to save memory. Thus, correctly implementing operator-> becomes non-trivial. Here is what I currently have (inspired by this Boost code linked from this question):

template<class ForwardIterator>
struct custom_input_iterator {

    typedef const std::basic_string<typename std::iterator_traits<ForwardIterator>::value_type> value_type;

    // All the other stuff required for an input iterator

    struct arrow_operator_proxy {
        explicit arrow_operator_proxy(value_type value)
        : value(value)
        {}

        const value_type * operator->() const {
            return &value;
        }
    private:
        value_type value;
    };

    arrow_operator_proxy operator->() const {
        // we can assume that this is a valid range here
        return arrow_operator_proxy(value_type(begin, current_sequence_end));
    }

private:
    ForwardIterator begin;
    ForwardIterator current_sequence_end;
};

I have two questions about this:

  1. Is this correct with respect to input iterator requirements and object lifetimes?
  2. Is there a simpler implementation?
Community
  • 1
  • 1
Björn Pollex
  • 75,346
  • 28
  • 201
  • 283
  • Why not have the iterator contain a pointer/reference to the actual value in the container? – Remy Lebeau Nov 17 '14 at 22:48
  • Also, the proxy needs to implement `operator value_type()` or `operator value_type&()` instead of `operator->()`. The users of your iterator are not going to write `iterator->->value`, they are going to write `iterator->value` instead. Look at the Boost code more carefully. – Remy Lebeau Nov 17 '14 at 22:50
  • The iterator works as an adapter. It exposes the underlying sequence as a sequence of objects of a different type. So I actually do store pointers into the underlying sequence, but I do the conversion on the fly when the iterator is dereferenced. – Björn Pollex Nov 17 '14 at 22:52
  • 1
    Also, the current implementation works due to the drill-down behaviour of [`operator->`](http://stackoverflow.com/a/8782794/160206) (I also have tests that confirm this). – Björn Pollex Nov 17 '14 at 22:53
  • 1
    I see no `value_type`, `begin` or `current_sequence_end` defined here. Can't we have a complete question? – Lightness Races in Orbit Nov 17 '14 at 23:18
  • @LightnessRacesinOrbit: Of course, I was lazy here. I've added the definitions required for context. – Björn Pollex Nov 19 '14 at 15:43

0 Answers0