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

前端 未结 7 1733
灰色年华
灰色年华 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

    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.

    0 讨论(0)
提交回复
热议问题