0

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?

nothingisme
  • 119
  • 5
  • Does this answer your question? [When would I pass const& std::string instead of std::string\_view?](https://stackoverflow.com/questions/39564457/when-would-i-pass-const-stdstring-instead-of-stdstring-view) – Stephen Newell Oct 01 '22 at 04:07
  • 1
    Your functions are incomplete. We cannot advise you because it's unclear whether the data you're returning is a temporary or has storage that exists outside of the function call. If the data is a `std::string` then consider returning `const std::string&` instead of copying. Nit-pick: std::string_view not a _keyword_ -- it's a type. – paddy Oct 01 '22 at 04:12
  • When you are asking about returning from a function, it is probably a bad idea to remove the `return` statement from your functions. Yes, omit the unnecessary details, but don't omit the detail that is the subject of your question. – JaMiT Oct 01 '22 at 04:25
  • *"will this cause crash?"* -- being aware of the crash possibility is good. What is your understanding of the circumstances that could lead to a crash? How well do these line up with your function? (If you need to, provide more details so that we can also see how well the crash scenario lines up with your function.) – JaMiT Oct 01 '22 at 04:30
  • Related, but a bit different (focuses on class members): [A: When should I use std::string / std::string_view for parameter / return type](https://stackoverflow.com/a/56648995) – JaMiT Oct 01 '22 at 04:42

1 Answers1

0

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.

relent95
  • 3,703
  • 1
  • 14
  • 17