Difference between std::basic_string_view<T> and std::span<T>
Asked Answered
D

1

7

I'm parsing a binary network data and i would like to make the process as allocation-less as possible. But now i realized there are 2 very similar concepts that are probably both good enough for my case, and those are std::basic_string_view<T> and std::span<T>.

So I was wondering. What are the differences between these 2 and are there any advantages using one over the other? One obvious difference is the availability, std::basic_string_view is already in C++17 while std::span is C++20 (but you can use the one in 'Guidelines Support Library' for older standards). But is there anything else? It should, because otherwise they wouldn't both make it into the standard.

Dooley answered 15/4, 2021 at 9:17 Comment(4)
string_view is span<char const> and has lots of string "convenience functions"Artemis
As @Artemis mentioned, string_view's API has operations that are similar to what std::string provides i.e. substr, copy, find etc.Thready
Same reason that both vector and basic_string existCracow
@AlanBirtles basic_string at least guarantees null-termination. That's not true for string_view (is there a null-terminated string_view planned?)Artemis
I
0

string_view is intended for use with textual data. span is intended for use with arbitrary arrays of objects. While neither one is an exact fit for binary data, string_view is clearly inapplicable.

Infringement answered 15/4, 2021 at 9:25 Comment(6)
I said basic_string_view, not string_view. The first one is a template and the second is one particular instance of that template with T=char.Dooley
The answer applies to basic_string_view and all of its instantiations.Infringement
Might want to mention the Traits parameterUnamuno
@Infringement I don't see how basic_string_view<uint8_t> is inapplicable for binary data, imo it's very well applicable.Dooley
I think @Dooley is correct, if basic_string_view points to a vector<T> or C style array like space, it should have the same feature like the string_view. I'm also try to use a view structure in my own parser design.Garibay
But why not just use span even for textual data, to be consistent?Adriell

© 2022 - 2024 — McMap. All rights reserved.