简体   繁体   中英

Invalid vector iterators

std::vector iterators can be implemented as pointers. A corollary is that if you add elements to the vector, outstanding iterators will obviously become invalid because in general the vector data will have to be reallocated.

A first guess regarding the exact rules would be that the allowed operations are exactly the same as those for pointers eg don't dereference an invalid iterator until it has been reassigned a valid value, but that doesn't seem to be quite true because Microsoft's implementation in debug mode will sometimes throw an exception if you eg subtract vector iterators pointing to different data blocks (which is helpful for debugging, to be sure).

Is the addendum to the pointer rules something like 'don't subtract iterators to different data blocks' or 'don't do any arithmetic on an invalid iterator until it has been reassigned a valid value' or something else?

For example, is the following program (which seems to work on both Microsoft C++ and GCC) valid?

#include <algorithm>
#include <iostream>
#include <vector>

using std::cout;
using std::ostream;
using std::vector;

template<class T> ostream& operator<<(ostream& os, vector<T>& v) {
    os << '[';
    bool c = 0;
    for (auto a: v) {
        if (c)
            os << ", ";
        c = 1;
        os << a;
    }
    return os << ']';
}

void f(vector<int>& v, vector<int>::iterator& i) {
    *i = 10;
    for (int j = 0; j < 10; j++)
        v.insert(begin(v), j);
    i = begin(v)+5;
}

int main() {
    vector<int> v;
    for (int i = 0; i < 10; i++)
        v.push_back(i);
    auto i = begin(v)+5;
    f(v, i);
    i[1] = 11;
    cout << v << '\n';
    return 0;
}

Your example is not valid, the reason why it works is luck. Every operation that can possibly cause a reallocation in a vector may invalidate all iterators.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM