Re: input iterators and post increment
On 2013-07-24 10:01, fmatthew5876 wrote:
I'm using input iterators to implement an asynchronous IO system.
Whenever you increment an input iterator, all copies of the previous
value can become invalidated. Indeed, this is the case in my example as
blocks of data come in and are released back to the system as the
iterator marches forward.
So my question in all this is why does the input iterator require post
increment?
The more specific requirement is that the expression
(void)r++
shall be valid and shall have the effects of being equivalent to
(void)++r
This means, that a valid implementation of the post-increment operator
for a pure input iterator could specify a return type of void.
It seems like an inherently broken and unsafe operation to support,
given that the only feature proffered by the useless return value is
the opportunity to write bugs by accidentally dereferencing it.
I agree that when we would start again with the iterator requirements,
we probably would rethink about the need to support post-increment, but
I think the right fix in your code would be to let this function return
void and to act exactly like pre-increment.
Would it break STL algorithms or in some other way be incorrect to only
implement pre-increment?
Maybe (but I really can't tell).
What about this variant?
void operator++(int);
This is already possible and would satisfy the required semantics.
Or just do the same as pre-increment?
iterator& operator++(int) { return ++(*this); }
This is also valid, but I really wouldn't recommend that, because it
gives an incorrect impression on the validity of operations.
If it must be implemented, perhaps the best practice is instead of returning
a copy of the previous iterator, return an iterator with some sentinel
values like setting all of its internal pointer data members to nullptr and
then asserting on that in the dereference.
Just return void and you are done.
HTH & Greetings from Bremen,
Daniel Kr?gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]