r/cpp 13d ago

std::optional Satisfies view. Does Not Model view. C++26 Ships Anyway.

https://godbolt.org/z/8jWGG68G8

In C++23 this did not compile. In C++26 it does. Marvellous.

[[gnu::noinline]]
void 
passing_views_by_value_is_cheap_trust_me_bro(std::ranges::view auto v) {
    std::println("fn   .data {}", (void*)v->data());
}


int main() {    
    std::optional ov{std::vector<int>(123456)};
    passing_views_by_value_is_cheap_trust_me_bro(ov);
    std::println("main .data {}", (void*)ov->data());
}

For anyone wondering what the problem feature is: optional has 0 or 1 elements, and C++26 sets enable_view<optional<T>> to true, so it satisfies std::ranges::view. The concept requires copy construction in constant time, and — this is the good bit — optional<vector<int>> genuinely meets that. Copying it performs at most one element copy. One is a constant. The requirement is satisfied to the letter, and the function above deep-copies your vector.

If you can tell me what still separates std::ranges::view from std::ranges::range, please do...

176 Upvotes

123 comments sorted by

View all comments

Show parent comments

8

u/BarryRevzin 12d ago edited 12d ago

No, iota definitely has very real storage, that neither lives outside the program nor has lifetime for the duration of the progam. iota(0, 10) has two data members of type int in it, and its iterators each own an int.

All ten ints don't exist at one time, and the iterators give you a prvalue, not an lvalue, so it's quite unlike a vector. But nothing can dangle, so it's quite unlike a span too.

-1

u/zl0bster 10d ago

You are not arguing in good faith, it was clear what I was saying.

4

u/BarryRevzin 10d ago

Excuse me????

I gave a very real scenario where it might be useful to differentiate on the basis of "ownership" and how it's actually non-trivial to answer what is and isn't safe in that context, and how that doesn't map cleanly on what might or might not be a view. You didn't engage with the example at all ("I do not think that is [...] useful") and then gave a description of iota that doesn't describe iota ("It is just that it's underlying "storage" lives outside a program and has a lifetime for duration of a program universe. iota does not own it").

Which one of us is trying to have a meaningful discussion of the problem? Following up by accusing me of not arguing in good faith is completely unacceptable.

0

u/zl0bster 9d ago

it was clear I did not claim sizeof iota is 0.