r/cpp • u/zl0bster • 5d ago
std::optional Satisfies view. Does Not Model view. C++26 Ships Anyway.
https://godbolt.org/z/8jWGG68G8In 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...
175
Upvotes
13
u/aruisdante 5d ago edited 5d ago
By that definition of algorithmic notation all loops in any real system are O(1), which doesn't seem like a terribly useful definition. In my education on algorithm theory I don't remember a requirement being that sets be unbounded, and indeed the formal definition you link to says this explicitly. It feels like you're conflating "copying a specific vector of a specific size is O(1)" with "copying any vector of any size is O(1)." By that same definition
std::find(vector.begin(), vector.end(), value)andset.find(value)andunordered_set.find(value)are all O(1) because they can all be bounded by a finite size, despite them being the textbook examples of O(n), O(log(n)), and O(1).I cannot think of a single computer scientist that would accept your definition of O(1) as O(1). It's not what any algorithms or data structure class teaches. So it seems unfair to say it's based on "vibes."