6

From what I can gather, gsl::string_span and std::string_view seem to have essentially the same rationale for use. Is that indeed the case? If so, are they effectively identical? If not - how do they differ?

Related question: What purpose does `gsl::string_span` aim at?

einpoklum
  • 118,144
  • 57
  • 340
  • 684

1 Answers1

3

How do gsl::string_span and std::string_view differ?

A rather obvious difference of how they are available, but I'll say it since it is significant: gsl::string_span requires the use of a third party library, while std::string_view is a standard C++ type. On the other hand, the library providing gsl::string_span supports C++14, while std::string_view requires C++17.

A major design difference is that std::string_view is a const view to the string, and doesn't provide any way of modifying the viewed string, while gsl::string_span does allow non-const access. For example:

constexpr iterator gsl::string_span::begin() const noexcept
          ^^^^^^^^ note non-const iterator   ^^^^^ also note this

Also note how gsl::string_span allows non-const access even when the span itself is const. in other words, gsl::string_span does not propagate constness. This is the same as std::span and gsl::span.

eerorika
  • 232,697
  • 12
  • 197
  • 326
  • 2
    Shouldn't `gsl::string_view` have been an endeavor to mimic the coming `std::string_view`? How come they diverged on something as significant as deep vs shallow constness? – einpoklum Jul 01 '19 at 19:25
  • 1
    @einpoklum I don't know; Should it have been? I don't know their rationale. I found a rationale for non-mutability of `std::string_view` here: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3762.html#mutable – eerorika Jul 01 '19 at 20:27
  • In A Tour of C++, 2nd ed., 2018, subsection 9.5, Bjarne Stroustrup says “Use string_view as an argument of functions that needs to read character sequences stored in various ways; Use gsl::string_span as an argument of functions that needs to write character sequences stored in various ways”. So we use gsl::string_span for 2 major reasons: 1. It does what std::string_view does and can be used in C++14 which is a version in which many production code is (obviously more than C++17); 2. It allows us to modify the content of the string, a thing that std::string_view doesn’t. – Maf Feb 24 '23 at 08:31