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

前端 未结 7 2233
迷失自我
迷失自我 2021-02-11 11:43

Suppose we have a string

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

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

7条回答
  •  死守一世寂寞
    2021-02-11 12:21

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

提交回复
热议问题