0

According to the description in cppreference.com:

The class template basic_string_view describes an object that can refer to a constant contiguous sequence of char-like objects with the first element of the sequence at position zero.

However, it could be useful to use that class template with non-const char pointers, for example to write to a null-terminated byte string using the standard algorithms. For example, imaging an hypotetical std::editable_string_view owning a char*, one could write something like

void filler(char *str, std::size_t len, char c) {
    std::editable_string_view sv(str, len);
    std::fill(sv.begin(), sv.end(), c);
}

Are there reasons for std::basic_string_view to support only const pointers?

Giovanni Cerretani
  • 1,693
  • 1
  • 16
  • 30
  • 3
    You might want to take a look at all the debate over `std::span` considering that's what this is, but not string-specific. – chris Oct 30 '19 at 13:25
  • If you are using `cstring`s, why not use `memset`? I mean, you're talking about doing C operations in C++... use `std::string` – JHBonarius Oct 30 '19 at 13:27
  • 4
    Hint: The answer is in the name. *view*ing something shouldn't change it (unless we are talking about my cat in a box ;-) ) – NathanOliver Oct 30 '19 at 13:27
  • Why not use `std::fill(str, str + len, c);` What't the advantage of string view here (if it were mutable)? – eerorika Oct 30 '19 at 13:31
  • string view is not used for modifying strings. You can use it on none const strings. – Marek R Oct 30 '19 at 13:34
  • @chris very interesting the `std::span` solution. Since I can't use C++20 yet, are there alternatives in Boost, as far as you know? – Giovanni Cerretani Oct 30 '19 at 13:37
  • 1
    @GiovanniCerretani See [What is a “span” and when should I use one?](https://stackoverflow.com/q/45723819/580083). – Daniel Langr Oct 30 '19 at 13:41
  • 1
    @GiovanniCerretani, Not that I know of, although there should be a number of light implementations on GitHub. However, it's not a drop-in replacement for `std::string` like `std::string_view` is. The reason I bring it up is that much of the discussion regarding whether `std::span` should be mutable applies to `std::string_view`'s design and you'll be sure to find points you haven't considered by researching those blog posts, talks, and papers. – chris Oct 30 '19 at 13:46
  • i think i get what you want. yeah it seems useful on some ways. but `std::string_view` is for viewing only. if you want to modify a substring that also modifies the source-string, it should not be string_view. it's should be a different class. you can search from a third party library or you create your own. – acegs Oct 30 '19 at 13:49

0 Answers0