rspec/rules/S6178/cfamily/rule.adoc
2023-10-09 13:50:05 +02:00

40 lines
1.2 KiB
Plaintext

== Why is this an issue?
In {cpp}20, ``++std::string++`` and ``++std::string_view++`` gain new member functions ``++starts_with++`` and ``++ends_with++`` that compare their argument to the prefix and postfix of the string.
These two functions introduce a standard, concise, and efficient way of checking the prefix and postfix for strings. The ad-hoc implementations predating {cpp}20 are often less readable, less efficient, and less reliable.
This rule raises an issue when an ad-hoc implementation checks prefixes or postfixes of a string.
=== Noncompliant code example
[source,cpp]
----
if (6 <= str.size() && str.substr(0, 6) == "prefix") { // Noncompliant
std::cout <<str <<" starts with the prefix\n";
}
if (6 <= str.size() && std::string_view(str.begin(), str.begin() + 6) == "prefix") { // Noncompliant
std::cout <<str <<" starts with the prefix\n";
}
if (7 <= str.size() && str.substr(str.size() - 7) == "postfix") { // Noncompliant
std::cout <<str <<" ends with the postfix\n";
}
----
=== Compliant solution
[source,cpp]
----
if (str.starts_with("prefix")) {
std::cout <<str <<" starts with the prefix\n";
}
if (str.ends_with("postfix")) {
std::cout <<str <<" ends with the postfix\n";
}
----