Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does reverse_iterator have a default constructor?

Tags:

c++

stl

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?

like image 658
wind2412 Avatar asked Sep 17 '17 16:09

wind2412


2 Answers

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.

like image 60
Passer By Avatar answered Nov 10 '22 04:11

Passer By


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.

like image 43
Nir Friedman Avatar answered Nov 10 '22 02:11

Nir Friedman