I start experiment with std::string_view
.
It has a very ugly feature. You cannot say:
std::string_view<const char>
and std::string_view<char>
like the awesome std::span
.
So, you cannot take a modifiable view from an std::string
and change some chars (You can get a non-modifiable from a const std::string
). Neither from char*
.
Is there any reason for this, or is it ...bad design?
Making std::string_view
, or more specifically, the class template std::basic_string_view<T>
potentially a mutable view was considered, but not deemed important.
To cite the proposal N3921: string_view
: a non-owning reference to a string, revision 7:
Make basic_string_view mutable
… and use
basic_string_view<const char>
for the constant case. The constant case is enough more common than the mutable case that it needs to be the default. Making the mutable case the default would prevent passing string literals intostring_view
parameters, which would defeat a significant use case forstring_view
. In a somewhat analogous sitation, LLVM defined anArrayRef
class in Feb 2011, and didn't find a need for the matchingMutableArrayRef
until Jan 2012. They still haven't needed a mutable version ofStringRef
. One possible reason for this is that most uses that need to modify a string also need to be able to change its length, and that's impossible through even a mutable version ofstring_view
.We could use
typedef basic_string_view<const char> string_view
to make the immutable case the default while still supporting the mutable case using the same template. I haven't gone this way because it would complicate the template's definition without significantly helping users.
In summary, a mutable string-view would complicate the template, would not be able to change the length of the string, and is not a sufficiently common use case.
Obviously, C++20 gives you std::span
for a possibly mutable view of a contiguous sequence, which can be used instead.
std::span
killed any motivation for some mutable string-view to be added.