Why does reverse_iterator have a default constructor?

I'm just learning STL, and reverse_iterator bothers me. 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 that there is no point in this use, and this can lead to a crash, so why is the default constructor allowed for use?

+5
source share
2 answers

std::reverse_iterator bidirectional iterators that have a clear requirement that they be constructive by default.

As for why bidirectional iterators are constructive by default , this is mainly because they are almost certainly trivial to implement, and providing such guarantees makes it easier to implement the algorithms.

Writing things like int* p = nullptr; *p; int* p = nullptr; *p; is itself UB, it violates the precondition that p can be dereferenced, allowing the adapters to "accept" such types of behavior quite naturally.

+3
source

The cppreference documentation says:

1) The default constructor. the current is initialized to a value. Operations on the resulting iterator determined the behavior if and only if the corresponding operations with the initialized value of the Iterator also determined the behavior.

There are several iterators that make sense to create by default; usually not those that are directly related to containers (what I know). For example, the istream iterator: http://en.cppreference.com/w/cpp/iterator/istream_iterator/istream_iterator . However, it is not bidirectional, so you cannot cancel it.

However, in principle, you can have an iterator that is bidirectional, and whose default constructor / initializer has at least certain operations. For such an iterator, you want the behavior to be reflected through reverse_iterator .

+3
source

Source: https://habr.com/ru/post/1271886/


All Articles