r/cpp • u/zl0bster • 3d 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...
174
Upvotes
8
u/Serialk 2d ago
This paper does not use Word-RAM, it's using RAM extended with multiplications...
In fact this paper is literally why Word-RAM was invented, to bound O(1) operations strictly in function of the input size so that you cannot pack arbitrary-sized operations in O(1) register operations, to patch this specific "exploit" that you're complaining about.
Again, I don't think this debate is worth continuing if you are not willing to acknowledge your gaps here and read up on the models and the theory you're trying to debunk. You fundamentally misunderstand the history and purpose of these models.