
Inline adoc files when they are included exactly once. Also fix language tags because this inlining gives us better information on what language the code is written in.
59 lines
1.4 KiB
Plaintext
59 lines
1.4 KiB
Plaintext
== Why is this an issue?
|
|
|
|
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
|
|
|
|
[source,cpp]
|
|
----
|
|
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
|
|
|
|
[source,cpp]
|
|
----
|
|
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[]
|