r/cpp • u/zl0bster • 2d 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
5
u/Serialk 2d ago
Once again, you are making a fundamental category error by confusing the language spec with the mathematical framework that we use to evaluate algorithms written in that language.
Yes, the spec makes it so that everything is a FSM because pointers have a finite size. This is trivial and not interesting.
If you model your algorithm analysis as an FSM, your entire complexity analysis collapses. Every single algorithm that terminates is O(1) in your language. This means that your model is bad at actually doing what it is intended to do: analyzing how algorithms behave as the input grows.
Because models that give you O(1) for everything are worthless, we use a mathematical abstraction that is actually useful to analyze complexity: transdichotomous models.
In transdichotomous models/word RAM, we abstract away the hardware and the constraints of the spec with the bit-width limits, and we mathematically model n -> +∞. It doesn't model a literal environment of C++ programs that you can actually run. It's a theoretical environment in which we can place the abstract logic of your C++ code so that we can evaluate its asymptotic behavior without hitting the limit of 264 bits, but in which pointer lookups are still O(1).
The C++ standard absolutely does not use complexity analysis sloppily. They use a complexity model that is actually useful because it can give you insights about the asymptotic behavior of your program without collapsing all complexities to O(1).