Iterators for basic_string/vector

Nathan Myers ncm@best.com
Thu Dec 30 07:30:00 GMT 1999


Benjamin Kosnik wrote: 
> Although I believe these iterator classes are useful, I would like to
> figure out a way to implement them that involves the least ammount of code
> duplication, both between the interator and const_iterator classes, and
> between string and vector (where the classes will eventually be used.) 
> ... 
> I don't really see any real reason to have separate classes for
> const_iterator and iterator. In particular, it is not required by the
> standard. 

I'm afraid I must disagree here.  This is a quality-of-implementation
issue.  For pure conformance, raw pointers are sufficient.  If we 
define classes, they should provide some benefit in compile-time 
error detection.  To get that, they must be distinct types so that 
trying to do something that should be illegal can in fact be illegal.  

As an option, they might even (according to a compile-time option) do
bounds-checking at run time.  However, that can (and probably should)
be added later.

IMHO, the code to implement these iterators is so small and so obvious 
that duplicating it is a relatively minor concern.  Still, a base-class
template could certainly be used to group the common operations and
minimize such duplication.

> // NB--why did vector and string not get designed with iterator as a
> // class? Does SGI have a reason besides expedience for the current
> // implementation with vector? Nathan or Matt, can you weigh in here?

Had they been specified as classes it would have been necessary to 
specify the class in the standard, which would have added a lot
of text.  Anyway, the spec should have made type violations ill-formed, 
so that raw pointers would not be a conforming implementation.
 
Nathan Myers
ncm@cantrip.org



More information about the Libstdc++ mailing list