rspec/rules/S1155/cfamily/rule.adoc
Fred Tingaud 22b4470f2a
Modify CFamily rules: CPP-4080 Refresh and standardize CppCoreGuidelines references (#3514)
Update all links to C++ Core Guidelines to `e49158a`.

Refresh done using the following script and some manual edits:
db76e34e74/personal/fred-tingaud/rspec/refresh-cppcoreguidelines.py

When re-using this script, be mindful that:
 - it does not cover `shared_content`
 - it does not properly escape inline code in links (e.g., "[=]" or "`mutex`es")
 - it does not change `C++` to `{cpp}` in link titles.

Co-authored-by: Marco Borgeaud <marco.borgeaud@sonarsource.com>
2023-12-20 10:08:18 +01:00

50 lines
1.6 KiB
Plaintext

== Why is this an issue?
When you call `empty()` or `is_empty()`, it clearly communicates the code's intention, which is to check if the collection is empty. Using `size() == 0` for this purpose is less direct and makes the code slightly more complex.
Moreover, depending on the implementation, the `size()`, `length()`, or `count()` methods can have a time complexity of `O(n)` where `n` is the number of elements in the collection. On the other hand, `empty()` and `is_empty()` simply check if there is at least one element in the collection, which is a constant time operation, `O(1)`.
[source,cpp,diff-id=1,diff-type=noncompliant]
----
void fun(const std::vector<int> &myVector) {
if (myVector.size() == 0) { // Noncompliant
// do something
}
}
----
Prefer using `empty()` or `is_empty()` to test for emptiness over `size()`, `length()`, or `count()`.
[source,cpp,diff-id=1,diff-type=compliant]
----
void fun(const std::vector<int> &myVector) {
if (myVector.empty()) {
// do something
}
}
----
== Resources
=== External coding guidelines
* {cpp} Core Guidelines - https://github.com/isocpp/CppCoreGuidelines/blob/e49158a/CppCoreGuidelines.md#t143-dont-write-unintentionally-non-generic-code[T.143: Don't write unintentionally non-generic code]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Use empty() or is_empty() to check whether the container is empty or not.
'''
== Comments And Links
(visible only on this page)
include::../comments-and-links.adoc[]
endif::env-github,rspecator-view[]