5

On the cppreference page of reverse_iterator I find the following remark

std::reverse_iterator does not work with iterators that return a reference to a member object (so-called "stashing iterators"). An example of stashing iterator is std::filesystem::path::iterator.

Is that claim correct? And, if yes, why is that?

To me the restriction makes no sense, as I would assume that the reverse iterator basically swaps the operator ++ and operator -- (and stores the underlying iterator off by one).

EDIT: Apparently the question can be mis-understood: I understand that we need the decrement operation once to implement a reverse iterator. The question is why this is not implemented during construction of the reverse_iterator. Then the problem with the stashing iterator is avoided. But apparently this is not how it is done, and the decrement is done every time the iterator is dereferenced. Why?

curiousguy
  • 8,038
  • 2
  • 40
  • 58
Andreas H.
  • 5,557
  • 23
  • 32
  • https://stackoverflow.com/questions/28595084/reference-invalidation-after-applying-reverse-iterator-on-a-custom-made-iterator –  Jun 13 '18 at 22:17

1 Answers1

4

and stores the underlying iterator off by one

That's the reason. You have to conjure a not-off-by-one iterator on dereference, and if destruction of the conjured iterator invalidates the reference obtained from it (as in the case of stashing iterators), then nasal demons.

T.C.
  • 133,968
  • 17
  • 288
  • 421
  • Ok, I see the misunderstanding. When I wrote `stored off-by-one` I meant that during construction of reverse_iterator the underlying iterator needs to be decremented.I understand that we need the decrement at some point to implement a reverse iterator, but I think it could be done once during construction. Then the problem you mention is avoided. Apparently this is not how it is done. So why is it not possible to use the during-construction-decremented iterator approach? Sorry if the question was unclear in that regard. – Andreas H. Jun 13 '18 at 22:33
  • @AndreasH. Because the iterator you get may not be decrementable. Consider `rend()`, which is constructed from `begin()`. – T.C. Jun 13 '18 at 22:36
  • :So you say that ` begin()` gives a non-decrementable iterator? – Andreas H. Jun 13 '18 at 22:41
  • @AndreasH. By definition, `begin()` gives an iterator to the beginning of the container, there is nothing "before" that position. – curiousguy Jul 02 '18 at 08:30