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

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

    Yes (str.empty() == (str == "")) is always* true for std::string. But remember that a string can contain '\0' characters. So even though the expression s == "" may be false, s.c_str() may still return an empty C-string. For example:

    #include 
    #include 
    using namespace std;
    
    void test( const string & s ) {
        bool bempty = s.empty();
        bool beq = std::operator==(s, ""); // avoid global namespace operator==
        const char * res = (bempty == beq ) ? "PASS" : "FAIL";
        const char * isempty = bempty ? "    empty " : "NOT empty ";
        const char * iseq = beq ? "    == \"\"" : "NOT == \"\"";
        cout << res << " size=" << s.size();
        cout << " c_str=\"" << s.c_str() << "\" ";
        cout << isempty << iseq << endl;
    }
    
    int main() {
        string s;          test(s); // PASS size=0 c_str=""     empty     == ""
        s.push_back('\0'); test(s); // PASS size=1 c_str="" NOT empty NOT == ""
        s.push_back('x');  test(s); // PASS size=2 c_str="" NOT empty NOT == ""
        s.push_back('\0'); test(s); // PASS size=3 c_str="" NOT empty NOT == ""
        s.push_back('y');  test(s); // PASS size=4 c_str="" NOT empty NOT == ""
        return 0;
    }
    

    **barring an overload of operator== in the global namespace, as others have mentioned*

提交回复
热议问题