6

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.

Jarod42
  • 203,559
  • 14
  • 181
  • 302
Youda008
  • 1,788
  • 1
  • 17
  • 35
  • 6
    `string_view` is `span` and has lots of string "convenience functions" – dyp Apr 15 '21 at 09:20
  • As @dyp mentioned, `string_view`'s API has operations that are similar to what `std::string` provides i.e. substr, copy, find etc. – Mansoor Apr 15 '21 at 09:26
  • 1
    Same reason that both `vector` and `basic_string` exist – Alan Birtles Apr 15 '21 at 12:10
  • @AlanBirtles `basic_string` at least guarantees null-termination. That's not true for `string_view` (is there a null-terminated string_view planned?) – dyp Apr 16 '21 at 07:42

1 Answers1

1

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.

Sneftel
  • 40,271
  • 12
  • 71
  • 104
  • 1
    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`. – Youda008 Apr 15 '21 at 09:46
  • 1
    The answer applies to `basic_string_view` and all of its instantiations. – Sneftel Apr 15 '21 at 10:16
  • Might want to mention the `Traits` parameter – Caleth Apr 15 '21 at 10:45
  • 2
    @Sneftel I don't see how `basic_string_view` is inapplicable for binary data, imo it's very well applicable. – Youda008 Apr 16 '21 at 09:06
  • I think @Youda008 is correct, if `basic_string_view` points to a `vector` 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. – ollydbg23 Jan 31 '23 at 09:02