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?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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 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: open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3762.html#mutable
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.