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

前端 未结 7 2224
迷失自我
迷失自我 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:31

    C++11 and beyond

    string_variable[0] is required to return the null character if the string is empty. That way there is no undefined behavior and the comparison still works if the string is truly empty. However you could have a string that starts with a null character ("\0Hi there") which returns true even though it is not empty. If you really want to know if it's empty, use empty().


    Pre-C++11

    The difference is that if the string is empty then string_variable[0] has undefined behavior; There is no index 0 unless the string is const-qualified. If the string is const qualified then it will return a null character.

    string_variable.empty() on the other hand returns true if the string is empty, and false if it is not; the behavior won't be undefined.


    Summary

    empty() is meant to check whether the string/container is empty or not. It works on all containers that provide it and using empty clearly states your intent - which means a lot to people reading your code (including you).

提交回复
热议问题