简体   繁体   中英

Does reverse_iterator inherit from iterator?

Let it be std::list::iterator and std::list::reverse_iterator . Is reverse one derived from forward? And if not then why there're not reverse equivalents for member functions of list ?

Thanks in advance.

Let it be std::list::iterator and std::list::reverse_iterator. Is reverse one derived from forward?

Not necessarily, they may (and probably are in most implementations) different types. Iterators are copied around all the time, and this inheritance would cause slicing. Plus, all operations on iterator should be virtual to avoid inconsistencies, which would be inefficient. Thinking about it, it would make sense for the standard to even forbid inheritance as a possible implementation (and maybe it does, indirectly).

Update: The standard provides a definition for std::reverse_iterator class template, and mandates that std::list::reverse_iterator is a specialization of such template. Inheritance is not a possible implementation.

And if not then why there're not reverse equivalents for member functions of list?

Because you can call base() on a reverse_iterator to get the underlying regular iterator . The fundamental relation between a reverse_iterator and its corresponding iterator i is that &*(reverse_iterator(i)) == &*(i - 1).

In GNU's implementation of the C++ standard library, there's a has-a relationship between a reverse_iterator and an iterator. (I haven't ever looked through the MSVC++ or llvm implementations, but I would imagine that they're the same.)

Basically, the reverse_iterator takes in an iterator and has a thin wrapper so that ++ aliases to -- and -- aliases to ++. Basically all of the operations are wrappers around the underlying non-reverse iterator.

And if not then why there're not reverse equivalents for member functions of list?

std::list does have a reverse iterator .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM