I'm just learning STL and reverse_iterator
has me confused. It has a default constructor but I don't understand how to use it.
I tried:
reverse_iterator<int*> r{};
r --;
and the program crashed. I believe there is no point to this usage and it can easily cause a crash, so why is the default constructor allowed to be used?
std::reverse_iterator
are bidirectional iterators, which have a distinct requirement that they be default-constructible.
As to why bidirectional iterators are default-constructible, it is mostly because it is almost certain they are trivial to implement and giving guarantees like this makes algorithms easier to implement.
Writing things like int* p = nullptr; *p;
is itself UB, it violates the precondition that p
be dereferenceable, letting adaptors "adopt" these kinds of behaviour is rather natural.
The documentation on cppreference says:
1) Default constructor. current is value-initialized. Operations on the resulting iterator have defined behavior if and only if the corresponding operations on a value-initialized Iterator also have defined behavior.
There are some iterators that are meaningful to be default constructed; usually not those that directly associated with containers (that I'm aware of). For example an istream iterator: http://en.cppreference.com/w/cpp/iterator/istream_iterator/istream_iterator. However, it's not bidirectional so you can't reverse it.
However, in principle, you could have an iterator that is both bidirectional, and whose default constructor/value initializer has at least some operations defined. For such an iterator, you'd want the behavior to be reflected through the reverse_iterator
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With