Can I make an assumption that given
std::string str;
... // do something to str
Is the following statement is always true?
(str.empty() == (str == ""))
Can I make an assumption that given
std::string str;
... // do something to str
Is the following statement is always true?
(str.empty() == (str == ""))
Yes
(str.empty() == (str == ""))
is always* true forstd::string
. But remember that astring
can contain'\0'
characters. So even though the expressions == ""
may be false,s.c_str()
may still return an empty C-string. For example:**barring an overload of
operator==
in the global namespace, as others have mentioned*Some implementations might test for the null character as the first character in the string resulting in a slight speed increase over calculating the size of the string.
I believe that this is not common however.
Yes it is equivalent but allows the core code to change the implementation of what empty() actually means depending on OS/Hardware/anything and not affect your code at all. There is similiar practice in Java and .NET
str.empty() is never slower, but might be faster than str == "". This depends on implementation. So you should use str.empty() just in case.
This is a bit like using ++i instead of i++ to increase a counter (assuming you do not need the result of the increment operator itself). Your compiler might optimise, but you lose nothing using ++i, and might win something, so you are better off using ++i.
Apart from performance issues, the answer to your question is yes; both expressions are logically equivalent.
Normally, yes.
But if someone decides to redefine an operator then all bets are off:
Answer
Yes. Here is the relevant implementation from
bits/basic_string.h
, the code forbasic_string<_CharT, _Traits, _Alloc>
: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 ofstd::string
, then==""
won't even compile, because you can't compare a string ofwchar_t
with one ofchar
. This, however, is not directly relevant to your original question, and I am 99% sure you will not switch tostd::wstring
.