Reputation: 2023
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.
Upvotes: 1
Views: 667
Reputation: 33437
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.
Upvotes: 1
Reputation: 81349
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).
Upvotes: 5