How can you use a reverse iterator with an iterator that is a proxy

187 views Asked by At

Given you have an iterator that is effectively a proxy and contains the data that it returns, how can you make a reverse iterator?

std::reverse_iterator implementation of the dereferencing operator creates a temporary object which it then decrements and dereferences, with code that is something like:

  reference operator*() const {
    iterator tmp = current;
    return *--tmp;
  }

with the result that what it returns to you is a pointer to data that goes out of scope before you get hold of it.

This has rather unfortunate results.

How can you get round this?

2

There are 2 answers

0
Pete On BEST ANSWER

It looks like you'll need to write your own custom reverse iterator implementation for this specific case since your iterator type is not compatible with this specific implementation of reverse_iterator.

According to http://en.cppreference.com/w/cpp/iterator/reverse_iterator, some implementations do also store a decremented copy of the iterator but not all. Boost::reverse_iterator does not appear to store an additional copy.

2
Simple On

I think the standard library implementation is incorrect. If you look at 24.5.1.3.4 [reverse.iter.op.star] in the C++11 standard you'll find the following:

deref_tmp = current;
--deref_tmp;
return *deref_tmp;

Note: This operation must use an auxillary member variable rather than a temporary variable to avoid returning a reference that persists beyond the lifetime of the associated iterator.

In the standard deref_tmp is a for-exposition-only data member of reverse_iterator.