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


Question

Can I make an assumption that given

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

Is the following statement is always true?

(str.empty() == (str == ""))
1
48
1/27/2009 1:18:35 PM

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.

52
5/23/2017 11:53:10 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon