Look at this example (taken from here):
class foo {
std::string my_str_;
public:
std::string_view get_str() const {
return my_str_.substr(1u);
}
};
This code is bad, because substr
returns a temporary std::string
, so the returned std::string_view
refers to an already-destroyed object. But, if substr
returned std::string_view
, this problem would not exist.
Besides, it seems logical to me if substr
returned std::string_view
instead of std::string
, because the returned string is a view of the string, and it is more performant, because no copy is made.
Would there be any drawbacks if substr
returned std::string_view
(besides the obvious drawback: losing some compatibility with C++14 - I'm not underrating the importance of this, I'd just like know whether other drawbacks exists)?
Related question: How to efficiently get a `string_view` for a substring of `std::string`