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

Will it be a good practice if I replace function return value from std::string to std::string_view?


I am learning c++17, I found std::string_view is a new keyword, which can improve std::string performance.

It can avoid copy, according to my understanding.

I have a lot of function, which return std::string, like this:

std::string handle_str(const std::string& s) {
  // hanlde
}

will it be good if i just replace with:

std::string_view handle_str(const std::string_view& s) {
  // hanlde
}

will this cause crash? and will it improve performance for free?


Solution

  • Generally No. It is OK, only if you are sure that the returned string_view instance is only used while the the original string which the string_view points to is alive. But that case will be rare. You need to understand the concept of a general view object. A view object is not a data owner or holder, so it cannot replace a string object in your business logic.

    The official documentation clearly says 'It is the programmer's responsibility to ensure that std::string_view does not outlive the pointed-to character array.' at notes.