Should I compare a std::string to “string” or “string”s?

前端 未结 3 1234
忘了有多久
忘了有多久 2021-01-31 07:41

Consider this code snippet:

bool foo(const std::string& s) {
    return s == \"hello\"; // comparing against a const char* literal
}

bool bar(const std::str         


        
3条回答
  •  礼貌的吻别
    2021-01-31 08:30

    From my understanding, this means that we will need to construct a std::string anyway in order to perform the comparison, so I suspect the overhead will be the same in the end (although hidden by the call to operator==).

    This is where that reasoning goes wrong. std::compare does not need to allocate its operand as a C-style null-terminated string to function. According to one of the overloads:

    int compare( const CharT* s ) const; // (4)
    

    4) Compares this string to the null-terminated character sequence beginning at the character pointed to by s with length Traits::length(s).

    Although whether to allocate or not is an implementation detail, it does not seem reasonable that a sequence comparison would do so.

提交回复
热议问题