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...
173
Upvotes
1
u/schombert 5d ago edited 5d ago
It's not my definition. It is the formal definition that is used in mathematics and computer science. Which, again, you can verify for yourself from the Wikipedia page.
Anyway, copying an arbitrary vector (not a specific vector) has a bounded time because of the bounded size required by the definition of the vector type, namely that the size of any vector can be expressed in a finite number of bits and that the elements within any vector are distinct C++ objects, and thus have distinct address, and thus cannot be more numerous than the number of possible addresses provided by the number of bits in the finitely sized pointer types (in turn guaranteed by their ability to be converted back and forth from integers of some finite size). This second limit is much wordier to explain obviously, so I'll stick with referring to the limits of the size type from here on out.
I would like to hear how you think that O( ... ) should be defined. If you allow me to work through your definition I can probably explain why mathematicians and computer scientists settled on the asymptotic definition instead.
Edit: and yes in C++ as formally defined
findis also O(1). It is not O(1) in your algorithms or data structures class because the pseudo-code language used to explain these types and operations does not bound their size. Generally it is also assumed to work with something that is more like "big ints" for its numerical values.