Consider this code snippet:
bool foo(const std::string& s) {
return s == \"hello\"; // comparing against a const char* literal
}
bool bar(const std::str
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.