rspec/rules/S5290/cfamily/rule.adoc

43 lines
1.2 KiB
Plaintext
Raw Normal View History

2021-04-28 16:49:39 +02:00
Iterators are useful to deal with data inside a container: they point to one of its element and can be incremented or decremented to access other elements of this container. However, they can be invalidated when their container is modified.
For example, iterators of ``++std::vector++`` are invalidated after an insertion which changed the capacity of the container, or if they point after an element of the ``++std::vector++`` which has just been erased.
Once an iterator has been invalidated, you can only assign a new value to it, but you should not increment, decrement or dereference it.
2021-04-28 16:49:39 +02:00
== Noncompliant Code Example
----
void test(std::list<int> &l1, std::list<int> l2) {
std::vector<int> v{1, 2, 3, 4, 5};
auto iter = v.begin();
v.erase(iter);
auto x = *iter; // Noncompliant, "iter" has been invalidated
auto iterList = l1.begin();
l1 = l2;
auto y = *iterList; // Noncompliant, "iterList" has been invalidated
// ...
}
----
2021-04-28 16:49:39 +02:00
== Compliant Solution
----
void test(std::list<int> &l1, std::list<int> &l2) {
std::vector<int> v{1, 2, 3, 4, 5};
iter = v.begin();
iter = v.erase(iter);
auto x = *iter; // Compliant
auto iterList = l1.begin();
auto y = *iterList; // Compliant
l1 = l2;
// ...
}
----