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?
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.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With