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

前端 未结 3 1268
忘了有多久
忘了有多久 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:37

    Neither.

    If you want to be clever, compare to "string"sv, which returns a std::string_view.


    While comparing against a literal like "string" does not result in any allocation-overhead, it's treated as a null terminated string, with all the concomittant disadvantages: No tolerance for embedded nulls, and users must heed the null terminator.

    "string"s does an allocation, barring small-string-optimisation or allocation elision. Also, the operator gets passed the length of the literal, no need to count, and it allows for embedded nulls.

    And finally using "string"sv combines the advantages of both other approaches, avoiding their individual disadvantages. Also, a std::string_view is a far simpler beast than a std::string, especially if the latter uses SSO as all modern ones do.


    At least since C++14 (which generally allowed eliding allocations), compilers could in theory optimise all options to the last one, given sufficient information (generally available for the example) and effort, under the as-if rule. We aren't there yet though.

提交回复
热议问题