简体   繁体   中英

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!

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{}; .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM