简体   繁体   English

C++:在 push_back 时迭代指针向量时出现分段错误

[英]C++: Segmentation fault while iterating over vector of pointers while push_back

I want to iterate through a vector of pointers pointing on objects.我想遍历指向对象的指针向量。 While iterating, I have to push_back new pointers to the vector.在迭代时,我必须 push_back 指向向量的新指针。 Before the loop, the number of push_backs is unknown and there is no abort criterion, so that I can't use a while loop.在循环之前,push_backs 的数量是未知的,也没有中止条件,所以我不能使用 while 循环。

Here is an example using pointers on integers, that shows the same error as the version with objects: Segmentation fault (core dumped) after one iteration.这是一个使用整数指针的示例,它显示了与带有对象的版本相同的错误:Segmentation fault (core dumped) after one iteration。

vector<int*> vec;
int a = 43;
vec.push_back(&a);

for (vector<int*>::iterator it = vec.begin(); it != vec.end(); ++it) {
    cout << *(*it) << " " << *it << endl;
    vec.push_back(&a);
}

The same Code but with integers works great.相同的代码但使用整数效果很好。

vector <int>vec;
int a = 43;
vec.push_back (a);

for (vector < int >::iterator it = vec.begin (); it != vec.end (); ++it){
    cout << (*it) << " " << *it << endl;
    vec.push_back (a);    
}

push_back invalidates the iterator when appending results in size > capacity so it reallocates and copies to the new space. push_back在追加结果时使迭代器无效, size > capacity ,因此它重新分配并复制到新空间。

Appends the given element value to the end of the container.将给定的元素值附加到容器的末尾。

1) The new element is initialized as a copy of value. 1) 新元素被初始化为值的副本。

2) value is moved into the new element. 2) 值被移动到新元素中。

If the new size() is greater than capacity() then all iterators and references (including the past-the-end iterator) are invalidated.如果新的 size() 大于 capacity() 则所有迭代器和引用(包括过去的迭代器)都将失效。 Otherwise only the past-the-end iterator is invalidated.否则只有过去的迭代器无效。

Plus as @Jesper pointed out you are storing a reference to a local variable in your vector :另外,正如@Jesper 指出的那样,您正在vector中存储对局部变量的引用:

int a = 43; 
vec.push_back(&a);

which if went out of scope before your vector you will have dangling references.如果在您的vector之前退出 scope,您将有悬空引用。

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

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