C++: is string.empty() always equivalent to string == “”?

前端 未结 7 1731
灰色年华
灰色年华 2020-12-28 12:18

Can I make an assumption that given

std::string str;
... // do something to str

Is the following statement is always true?

         


        
7条回答
  •  醉梦人生
    2020-12-28 12:47

    Answer

    Yes. Here is the relevant implementation from bits/basic_string.h, the code for basic_string<_CharT, _Traits, _Alloc>:

      /**
       *  Returns true if the %string is empty.  Equivalent to *this == "".
       */
      bool
      empty() const
      { return this->size() == 0; }
    

    Discussion

    Even though the two forms are equivalent for std::string, you may wish to use .empty() because it is more general.

    Indeed, J.F. Sebastian comments that if you switch to using std::wstring instead of std::string, then =="" won't even compile, because you can't compare a string of wchar_t with one of char. This, however, is not directly relevant to your original question, and I am 99% sure you will not switch to std::wstring.

提交回复
热议问题