Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are ForwardIterators required to model DefaultConstructible?

Tags:

c++

iterator

I cannot seem to find any standard algorithms that would demonstrate the requirement for default-constructing a ForwardIterator.

Is there any actual reason for it, or am I safe to ignore it?

like image 962
Ayjay Avatar asked May 01 '12 10:05

Ayjay


2 Answers

It is there to ease the use of these kind of iterators, for both the standard algorithms and client users.

For example (remember that RandomAccessIterator is a subtype of ForwardIterator):

template <class RandomAccessIterator>
  void sort ( RandomAccessIterator first, RandomAccessIterator last )
{
    RandomAccessIterator pivot, i, j;
    //do your sorting algorithm        
}

If they were not default constructible you would need to assign them to first or last just for it to compile.

You do not need it to be set to a default value. Any use of such uninitialized iterator is undefined. Not that is would not be wise to add some check, particularly in debug builds.

And no, you should not throw in the default constructor. It would be technically conformant, but many algorithms will fail unexpectedly.

like image 154
rodrigo Avatar answered Nov 13 '22 15:11

rodrigo


From my copy of the draft:

24.2.5 Forward iterators [forward.iterators]

1 A class or a built-in type X satisfies the requirements of a forward iterator if

[...]

— X satisfies the DefaultConstructible requirements (20.2.1),

and then:

20.2.1 Template argument requirements

2 In general, a default constructor is not required. Certain container class member function signatures specify the default constructor as a default argument. T() shall be a well-defined expression (8.5) if one of those signatures is called using the default argument (8.3.6).

There are two things to note here:

  • The first line tells us that a default ctor is rarely required (which almost answers your question)
  • The requirement is probably a hint that iterator semantics should be compatible with pointers, the latter being default constructible (read not to break existing code).
like image 42
dirkgently Avatar answered Nov 13 '22 15:11

dirkgently