Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is singular and non-singular values in the context of STL iterators?

The section §24.1/5 from the C++ Standard (2003) reads,

Just as a regular pointer to an array guarantees that there is a pointer value pointing past the last element of the array, so for any iterator type there is an iterator value that points past the last element of a corresponding container. These values are called past-the-end values. Values of an iterator i for which the expression *i is defined are called dereferenceable. The library never assumes that past-the-end values are dereferenceable. Iterators can also have singular values that are not associated with any container. [Example: After the declaration of an uninitialized pointer x (as with int* x;), x must always be assumed to have a singular value of a pointer.] 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 this case the singular value is overwritten the same way as any other value. Dereferenceable values are always nonsingular.

I couldn't really understand the text shown in bold?

  • What is singular value and nonsingular value? How are they defined? And where?
  • How and why dereferenceable values are always nonsingular?
like image 634
Nawaz Avatar asked Mar 26 '11 11:03

Nawaz


1 Answers

If I understand this correctly, a singular value for an iterator is essentially the equivalent of an unassigned pointer. It's an iterator that hasn't been initialized to point anywhere and thus has no well-defined element it's iterating over. Declaring a new iterator that isn't set up to point to an element of a range, for example, creates that iterator as a singular iterator.

As the portion of the spec alludes to, singular iterators are unsafe and none of the standard iterator operations, such as increment, assignment, etc. can be used on them. All you can do is assign them a new value, hopefully pointing them at valid data.

I think the reason for having this definition is so that statements like

set<int>::iterator itr;

Can be permitted by the spec while having standardized meaning. The term "singular" here probably refers to the mathematical definition of a singularity, which is also called a "discontinuity" in less formal settings.

like image 175
templatetypedef Avatar answered Sep 21 '22 20:09

templatetypedef