Suppose we have a string
std::string str; // some value is assigned
What is the difference between str.empty()
and str[0] =
Since C++11 it is guaranteed that str[str.size()] == '\0'
. This means that if a string is empty, then str[0] == '\0'
. But a C++ string has an explicit length field, meaning it can contain embedded null characters.
E.g. for std::string str("\0ab", 3)
, str[0] == '\0'
but str.empty()
is false.
Besides, str.empty()
is more readable than str[0] == '\0'
.