64 lines
1.9 KiB
Plaintext
64 lines
1.9 KiB
Plaintext
== Why is this an issue?
|
|
|
|
`std::string` and `std::string_view` provide functions to search for specific characters or groups of characters within a string. If the search is successful, these functions will return the position of the first character in the string that matches the search pattern. If the search fails, the functions will return the special value `npos`.
|
|
|
|
`npos` is converted to `true` when used in a boolean context. Therefore, using the returned value in a boolean context to determine if the search was successful does not work.
|
|
|
|
== How to fix it
|
|
|
|
The returned value of the following functions should be compared to `npos` when used in a boolean context:
|
|
|
|
* `find`
|
|
* `rfind`
|
|
* `find_first_of`
|
|
* `find_last_of`
|
|
* `find_first_not_of`
|
|
* `find_last_not_of`
|
|
|
|
|
|
=== Code examples
|
|
|
|
==== Noncompliant code example
|
|
[source,cpp,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
void f() {
|
|
std::string s = "";
|
|
if (s.find("42")) { // Noncompliant: the condition is true even if "s" does not contain "42"
|
|
// ...
|
|
}
|
|
}
|
|
----
|
|
|
|
==== Compliant solution
|
|
[source,cpp,diff-id=1,diff-type=compliant]
|
|
----
|
|
void f() {
|
|
std::string s = "";
|
|
if (s.find("42") != std::string::npos) {
|
|
// ...
|
|
}
|
|
}
|
|
----
|
|
|
|
== Resources
|
|
|
|
=== Documentation
|
|
|
|
* {cpp} reference - https://en.cppreference.com/w/cpp/string/basic_string[Search functions for std::basic_string]
|
|
* {cpp} reference - https://en.cppreference.com/w/cpp/string/basic_string_view[Search functions for std::basic_string_view]
|
|
* {cpp} reference - https://en.cppreference.com/w/cpp/string/basic_string/npos[std::basic_string<CharT,Traits>::npos]
|
|
* {cpp} reference - https://en.cppreference.com/w/cpp/string/basic_string_view/npos[std::basic_string_view<CharT,Traits>::npos]
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
=== Message
|
|
|
|
Compare the method result with std::(string|string_view)::npos.
|
|
|
|
|
|
endif::env-github,rspecator-view[]
|