Search code examples
c++c++17stdstringstring-view

What is the correct way to “clear" a std::string_view?


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!


Solution

  • 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())