Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this correct: std::views::reverse on infinite range?

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?

like image 904
PiotrNycz Avatar asked Dec 29 '21 15:12

PiotrNycz


1 Answers

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.

like image 124
康桓瑋 Avatar answered Oct 24 '22 01:10

康桓瑋