skgbanga skgbanga - 5 months ago 64
C++ Question

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

has given us
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&
. Consider the following example:

char foo(const std::string& str)
return str[0];

The above is a valid function for all values of
. 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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download