rspec/rules/S5290/cfamily/rule.adoc

59 lines
1.4 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
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.
=== Noncompliant code example
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,cpp]
2021-04-28 16:49:39 +02:00
----
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
// ...
}
----
=== Compliant solution
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,cpp]
2021-04-28 16:49:39 +02:00
----
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;
// ...
}
----
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
invalidated iterator accessed
endif::env-github,rspecator-view[]