简体   繁体   English

无效的向量迭代器

[英]Invalid vector iterators

std::vector iterators can be implemented as pointers. std::vector迭代器可以实现为指针。 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). 关于确切规则的第一个猜想是,允许的操作与指针的操作完全相同,例如在重新分配有效值之前不要取消引用无效的迭代器,但这似乎并不正确,因为Microsoft的如果您例如减去指向不同数据块的向量迭代器,则调试模式下的实现有时会引发异常(当然,这对调试很有帮助)。

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? 例如,以下程序(似乎可以同时在Microsoft C ++和GCC上运行)是否有效?

#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. 每个可能导致向量重新分配的操作都可能使所有迭代器无效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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