The difference between the indexing operator ([]) of a string and string_view

C++17gave us string_viewto optimize scenarios in which we were uselessly allocating memory when we needed only a representation of the basic 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 function is valid for all values std::string. However, if we change this to:

char foo(std::string_view sv)
{
    return sv[0];
}

We called Undefined Behavior 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 ().

- , ?

+6
1

, std::string NUL - . a std::string 0- .

std::string:

pos == size(), CharT() ( ).

http://en.cppreference.com/w/cpp/string/basic_string/operator_at

+8

All Articles