Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between indexing operator ([]) of string and string_view

Tags:

c++

c++17

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?

like image 528
skgbanga Avatar asked Sep 25 '17 04:09

skgbanga


1 Answers

The difference is a std::string is guaranteed to be NUL terminated - a view is not. Therefor a std::string always has a valid value at the 0th position.

For a std::string:

If pos == size(), a reference to the character with value CharT() (the null character) is returned.

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

like image 58
xaxxon Avatar answered Sep 18 '22 12:09

xaxxon