Problem
Calling std::distance(nullptr, nullptr) has ambiguous status in the C++ standard iterator.requirements.general:
Iterators can also have singular values that are not associated with any sequence. Results of most expressions are undefined for singular values.
It seems to work correctly in every implementation we use, but LWG 1213 (“Meaning of valid and singular iterator underspecified”) has been Open since 2009, acknowledging that the standard’s wording on this topic is unclear.
The iterator.requirements.general states:
Iterators can also have singular values that are not associated with any sequence. Results of most expressions are undefined for singular values.
And LWG 208’s rationale explicitly confirms:
Null pointers are singular.
Therefore they cannot form a valid range required by std::distance:
Preconditions: last is reachable from first, or InputIterator meets the Cpp17RandomAccessIterator requirements and first is reachable from last.
Fix
A previous version of this PR checked both values for nullptr, the current one uses unambiguously well-defined pointer subtraction instead, which is per expr.add:
If P and Q both evaluate to null pointer values, the value is 0.
This applies on the first call before any memory is allocated, when both pointers are nullptr.
Using operator- directly is simpler and avoids the ambiguity entirely.