Difference between string.empty and string[0] == '\0'

前端 未结 6 1638
予麋鹿
予麋鹿 2021-02-11 12:15

Suppose we have a string

std::string str; // some value is assigned

What is the difference between str.empty() and str[0] =

6条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-11 12:32

    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'.

提交回复
热议问题