std::distance
is missing a preconditionSection: 24.4.3 [iterator.operations] Status: New Submitter: Jan Schultke Opened: 2024-02-25 Last modified: 2024-03-12
Priority: 4
View other active issues in [iterator.operations].
View all other issues in [iterator.operations].
View all issues with New status.
Discussion:
std::distance
for random access iterators is defined in terms of
(last - first)
(24.4.3 [iterator.operations] p5) for
Cpp17RandomAccessIterators.
Table 91: Cpp17RandomAccessIterator requirements (in addition to Cpp17BidirectionalIterator) [tab:randomaccessiterator] Expression Return type Operational semantics Assertion/note
pre-/post-condition[…]
b - a
difference_type
return n;
Preconditions: there exists a
valuen
of typedifference_type
such thata + n == b
.
b == a + (b - a)
.
For example, pointer subtraction is undefined if the result isn't representable
as std::ptrdiff_t
, and user-defined types with random access iterators
aren't required to have a difference which is always representable by
difference_type
.
std::distance(&a, &b)
can't be well-defined when
&b - &a
is not, so std::distance
is missing a precondition.
[2024-03-12; Reflector poll]
Set priority to 4 after reflector poll.
The proposed change is wrong, the new wording only associates with the second
condition, but should also apply when "last
is reachable from
first
".
Previous resolution [SUPERSEDED]:
This wording is relative to N4971.
Modify 24.4.3 [iterator.operations] as indicated:
template<class InputIterator> constexpr typename iterator_traits<InputIterator>::difference_type distance(InputIterator first, InputIterator last);-4-Preconditions:
-5- Effects: Iflast
is reachable fromfirst
, orInputIterator
meets the Cpp17RandomAccessIterator requirements,andfirst
is reachable fromlast
, andtypename iterator_traits<InputIterator>::difference_type
can represent the result of this function call.InputIterator
meets the Cpp17RandomAccessIterator requirements, returns(last - first)
; otherwise, incrementsfirst
untillast
is reached and returns the number of increments.
[2024-03-12; Jonathan provides improved wording]
Proposed resolution:
This wording is relative to N4971.
Modify 24.4.3 [iterator.operations] as indicated:
template<class InputIterator> constexpr typename iterator_traits<InputIterator>::difference_type distance(InputIterator first, InputIterator last);-4-Preconditions:
-5- Effects: Iflast
is reachable fromfirst
, orInputIterator
meets the Cpp17RandomAccessIterator requirements andfirst
is reachable fromlast
. The return type can represent the result.InputIterator
meets the Cpp17RandomAccessIterator requirements, returns(last - first)
; otherwise, incrementsfirst
untillast
is reached and returns the number of increments.