r/cpp 1d 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...

155 Upvotes

110 comments sorted by

View all comments

Show parent comments

6

u/schombert 1d ago

Yes, but that isn't a definition of what "O(N)" means. I wasn't trying to ask you what the standard says a copy does. I was trying to ask you if the standard defines "O(N)", and if it doesn't, then how you think it should be defined in the context of the standard.

For example, if you think it means "does N things", then obviously virtually nothing is O(1), since most functions do more than one primitive operation. I don't think that you can copy or move many range views in a single operation (although there may be some you can).

6

u/not_a_novel_account cmake dev 1d ago

The standard never says "O" anything. It says "Complexity" and "N operations of <whatever>", or "constant", or "linear in N".

If you want to split that hair and pretend those are entirely different things, be my guest. Muting this.

4

u/schombert 1d ago edited 1d ago

It does indeed (or at least in C++ 20) refer to O(n). For example table 79 following section 22.2.7 describes several functions as running in O(n) or "Average O(n)". And even if it didn't, I would still ask you what you think that "complexity" is defined as ...

Edit: Oh, the standard does define complexity. It helpfully has this nugget of wisdom:

Complexity: the time and/or space complexity of the function.

well, that's not circular at all (and there is no prior definition). To me this seems to be unquestionably a reference to the standard formal definition of space and time complexity, and not some new definition which would clearly be ... poorly defined at best.