0

I see this post: c++ - Why doesn't std::string_view have assign() and clear() methods? - Stack Overflow, so string_view does not contain clear function.

But in my case, I have a string_view as a class member variable, and sometimes, I would like to reset it to an empty string. Currently, I'm using this way:

sv = "";

Which looks OK, but I'd see other suggestions, thanks!

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
ollydbg23
  • 1,124
  • 1
  • 12
  • 38
  • A string view isn't a container in itself, it's just a *view* of another string. As such, the assignment you show doesn't attempt to modify the other string, it merely makes the view reference another string. – Some programmer dude Jan 29 '23 at 12:15

2 Answers2

3

An empty "" string is still a string of length zero. While that will work, data() will not return a nullptr the way it would for a truly empty string_view. If you do want to reset the string_view, it would be best to assign an empty string_view to it: sv = string_view{};.

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
  • Thanks for the explanation, so the empty `string_view` which constructed from `{}` should be the best solution. – ollydbg23 Jan 30 '23 at 01:19
  • I'm not really happy with your idea of a "truly empty `string_view`". All `string_view`s of length zero compare equal. – Marshall Clow Jan 31 '23 at 02:05
1

If what you want is to set the size of the string_view to zero, then what you're doing is OK (at the cost of a byte somewhere in your binary).

There are alternatives in the post that you referenced:

  • sv = {}
  • sv = sv.substr(0, 0)

Yet another way:

  • sv.remove_prefix(sv.size())
Marshall Clow
  • 15,972
  • 2
  • 29
  • 45