Why is this an issue?
The functions of std::string
and std::string_view
that search inside the string return the character position, and use
the special value npos
if the pattern was not found. When converted to a boolean, npos
is equivalent to true
.
Therefore, testing if the search succeeded requires to compare the returned value to npos
, not to use it in a boolean context.
This rule raises an issue when the returned value the following functions are used in a boolean context:
-
find
-
rfind
-
find_first_of
-
find_last_of
-
find_first_not_of
-
find_last_not_of
Noncompliant code example
void f() {
std::string s = "";
if (s.find("42")) { // Noncompliant
// this branch is taken even if "s" doesn't contain "42"
}
}
Compliant solution
void f() {
std::string s = "";
if (s.find("42") != std::string::npos) {
// this branch is correctly not taken
}
}