Reputation: 105
Are there any advantages for std::string_view over char* other than the std::string_view methods?
Are there any reasons to re-factor char*
into string_view
if none of string_view
's methods would be used?
Upvotes: 2
Views: 776
Reputation: 275405
A char*
is just a pointer to a character. For it to be interpreted as a string you need a length, either explicit (pascal strings store it before the first character, or you could pass length information beside it as another argument or struct member), or implicitly (null termination).
A string view is an abstraction of the 2nd of the above. Unlike the 1st or 3rd, it does not require data contiguous to the string buffer to contain length information. This means you can create non-owning substrings in O(1) time without copying, something the other two approaches cannot do.
Determining the length of a string for 1st and 2nd case above is O(1) and O(n) for null termination. This matters.
The string view has no fundamental advantages over a pair of char*
or a char*
paired with a length; all you gain compared to those is the utility methods. But it is fundamentally different than a null terminated char buffer.
Upvotes: 9