Re: Copying singular iterators
Sylvain Pion wrote:
Hi,
[24.1.5] states :
<< ... Results of most expressions are undefined for singular values;
the only exception is an assignment of a non-singular value to an
iterator that holds a singular value. ... >>
In practice, the debug mode of GCC's STL checks for this at run-time,
so that code like the following fails at run-time:
std::list<int>::iterator it1, it2;
it1 = it2;
Note that Visual C++'s debug mode does not seem to check for that.
I am wondering why there is such a strict requirement on singular values
of iterators. Iterators are meant to be small pointer-like objects,
and I can't see any useful reason to disallow copies/assignments of
singular values (which would of course propagate the "singular-ness").
In practice, sometimes you want to store iterators, e.g. in containers,
or other places where you will do copies, and it is a pain to have to
take care of this issue for no visible gain.
People have a tendency to assume that a singular value for an iterator
corresponds to a null value for a pointer. What it really corresponds
to is an uninitialized value. Consider the following code:
int *p;
At this point, the value of 'p' is uninitialized. The only operations
that can legally be performed on it are precisely the same operations
that are permitted for singular iterators. In particular, consider a
simple copy assignment:
int *q = p;
On many real platforms, the copy will be performed by loading it's
uninitialized value from memory into an address register, and then
writing the value of that register into the memory containing 'q'. On
many of those platforms, the load into the address register performs a
validity check on the address value, and if it's invalid, aborts your
program. This is a deliberate feature of those platforms, designed to
limit the amount of damage performed by code that is so poorly written
as to attempt to load invalid addresses into an address register. The
standard says that the behavior of such code is undefined, permitting
such implementations.
The standard extends this concept to singular iterators, permitting
pointers to qualify as iterators on such implementations. It also
permits implementation of iterators as user-defined types with similar
characteristics.
---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html ]