C++17 has given us string_view to optimise the scenarios where we were needlessly allocating memory when we only need a view of the underlying sequence of characters. The wisdom is that you can almost always replace const std::string& with std::string_view. Consider the following example:
char foo(const std::string& str)
{
return str[0];
}
The above is a valid function for all values of std::string. However, if we change this to:
char foo(std::string_view sv)
{
return sv[0];
}
We have triggered Undefined Behaviour for strings of size 0! This has a note at the end:
Unlike std::basic_string::operator[], std::basic_string_view::operator[] (size()) has undefined behavior instead of returning CharT().
Does anyone know why the behaviour is incongruous for the indexing operator?
str[0]also undefined, same as*begin()orfront()? - Tasstr[0]was undefined inc++03. However, inc++11forpos == size(), a reference to character with value CharT() is returned. More details here: en.cppreference.com/w/cpp/string/basic_string/operator_at - skgbangastring_viewcomes to mind - Passer By