5

See this example code:

#include <ranges>

int main() {
    for(auto i : std::ranges::iota_view(1) | std::views::reverse) 
        break;
}

It compiles on gcc (I cannot check on clang/msvc - since they do not support ranges). Of course -- it runs "forever" and does nothing.

I also checked that doing std::ranges::rbegin(inf) or std::ranges::rend(inf) on infinite range is not allowed (it does not compile).

I am not sure if this is correct c++ code? And I am curious about std::ranges::reverse implementation - looks like rbegin/rend is not used to implement this view -- so how this implementation works?

PiotrNycz
  • 23,099
  • 7
  • 66
  • 112

1 Answers1

4

According to [iterator.requirements.general-10]:

A sentinel s is called reachable from an iterator i if and only if there is a finite sequence of applications of the expression ++i that makes i == s. If s is reachable from i, [i, s) denotes a valid range.

And [iterator.requirements.general-12]:

The result of the application of library functions to invalid ranges is undefined.

Since ranges::iota_view(1) is not a valid range, applying views::reverse to it is undefined behavior.

康桓瑋
  • 33,481
  • 5
  • 40
  • 90
  • So, not all ranges in std library are valid per definition. Interesting idea. From deleted @Artyer answer I read that `ranges::next(ranges::begin(base_), ranges::end(base_)) ` is used to implement reverse for ranges with sentinel end iterator. The question: could the c++ std be improved by requiring that "application of library functions to invalid ranges" is not allowed (i.e. will not compile) instead of just say "undefined"? – PiotrNycz Dec 30 '21 at 08:42
  • 1
    @PiotrNycz. That is an improvement. But the current standard does *not* have so-called "infinite range" (only range-v3 has), because it is very different from the "traditional" container and is not suitable for standard algorithms, so the introduction of the concept of "infinite range" requires a paper, which is also why the current standard only defines it as undefined behavior. – 康桓瑋 Dec 30 '21 at 09:02