|
| 1 | +<?xml version='1.0' encoding='utf-8' standalone='no'?> |
| 2 | +<!DOCTYPE issue SYSTEM "lwg-issue.dtd"> |
| 3 | + |
| 4 | +<issue num="4242" status="New"> |
| 5 | +<title>`ranges::distance` does not work with volatile iterators</title> |
| 6 | +<section> |
| 7 | +<sref ref="[range.iter.op.distance]"/> |
| 8 | +</section> |
| 9 | +<submitter>Hewill Kang</submitter> |
| 10 | +<date>12 Apr 2025</date> |
| 11 | +<priority>99</priority> |
| 12 | + |
| 13 | +<discussion> |
| 14 | +<p> |
| 15 | +After LWG <iref ref="3664"/>, `ranges::distance` computes the distance between `last` and `first` |
| 16 | +by returning <code>last - static_cast<const decay_t<I>&>(first)</code> when the |
| 17 | +two are subtractable. However, this will cause a hard error if <code>first</code> is volatile-qualified |
| 18 | +(<a href="https://godbolt.org/z/5M3d9rMjE">demo</a>): |
| 19 | +</p> |
| 20 | +<blockquote><pre> |
| 21 | +#include <iterator> |
| 22 | + |
| 23 | +int main() { |
| 24 | + int arr[] = {1, 2, 3}; |
| 25 | + int* volatile ptr = arr; |
| 26 | + // return std::distance(ptr, arr + 3); // this is ok |
| 27 | + return std::ranges::distance(ptr, arr + 3); // <span style="color:#C80000;font-weight:bold">hard error</span> |
| 28 | +} |
| 29 | +</pre></blockquote> |
| 30 | +<p> |
| 31 | +The resolution changes the <i>Effects</i> of LWG <iref ref="3664"/> from "cute" to "noncute". |
| 32 | +</p> |
| 33 | +</discussion> |
| 34 | + |
| 35 | +<resolution> |
| 36 | +<p> |
| 37 | +This wording is relative to <paper num="N5008"/>. |
| 38 | +</p> |
| 39 | + |
| 40 | +<ol> |
| 41 | + |
| 42 | +<li><p>Modify <sref ref="[range.iter.op.distance]"/> as indicated:</p> |
| 43 | + |
| 44 | +<blockquote> |
| 45 | +<pre> |
| 46 | +template<class I, sized_sentinel_for<decay_t<I>> S> |
| 47 | + constexpr iter_difference_t<decay_t<I>> ranges::distance(I&& first, S last); |
| 48 | +</pre> |
| 49 | +<blockquote> |
| 50 | +<p> |
| 51 | +-3- <i>Effects</i>: Equivalent to: |
| 52 | +</p> |
| 53 | +<pre> |
| 54 | +<ins>if constexpr (!is_array_v<remove_reference_t<I>>) |
| 55 | + return last - first; |
| 56 | +else</ins> |
| 57 | + return last - static_cast<<del>const</del> decay_t<I><del>&</del>>(first); |
| 58 | +</pre> |
| 59 | +</blockquote> |
| 60 | +</blockquote> |
| 61 | + |
| 62 | +</li> |
| 63 | + |
| 64 | +</ol> |
| 65 | +</resolution> |
| 66 | + |
| 67 | +</issue> |
0 commit comments