简体   繁体   English

使用迭代器擦除元素时,std :: deque内存损坏

[英]std::deque memory corruption when using iterator to erase elements

My code occasionally crashes because of the following 由于以下原因,我的代码有时会崩溃

//queue is a std::shared_ptr<std::deque<Something> >
//I can guarantee that queue will never be empty.
std::deque<Something>::iterator it = queue->end();
it--;
queue->erase(it);

Not always, but sometimes. 并非总是如此,但有时。 It happens mostly after I added something to the front then try to delete the back. 发生这种情况的主要原因是,我在前端添加了一些内容,然后尝试删除后端。

If I change it to 如果我将其更改为

queue->pop_back();

At lease haven't seen it crashing for a long time. 至少没有看到它崩溃了很长时间。

But can anyone enlighten me why the former code will crash? 但是谁能启发我为什么以前的代码会崩溃? I guess it is something related to the fact that resizing may invalidate all iterators. 我猜这与调整大小可能会使所有迭代器无效的事实有关。 But what I did was -- not ++ . 但是我所做的是--不是++

Can anyone please explain to me why? 谁能向我解释为什么?

//----------------------- // ------------------------

// Update //更新

//----------------------- // ------------------------

My understanding is it is just a pointer. 我的理解是, it仅仅是一个指针。 There is no insertion, between getting it and using it . 没有插入,越来越之间it并使用it

The only operation is it-- . 唯一的操作是it-- But since it-- is a pointer moving. 但是it--指针在移动。 We always do 我们总是做

for(it = xxx.begin(); it!=xxx.end(); ++it)
{
    ...
}

It works fine. 工作正常。 Or is the following illegal? 还是以下违法行为?

for(it=xxx.end();it!=xxx.begin();--it){...}

What I don't understand is why a pointer moving in the valid range, will cause memory corruption. 我不明白的是,为什么指针在有效范围内移动会导致内存损坏。

Because after -- , it points the exact element I want, there is no way to re-get this pointer unless I just use ( xxx.end()-1 ) instead. 因为在--之后, it指向我想要的确切元素,所以除非我只使用( xxx.end()-1 )否则无法重新获取该指针。

Thanks 谢谢

If your queue is not empty - everything is fine with your code. 如果您的队列不为空-代码就可以了。

Your statement about reverse iterating 您关于反向迭代的声明

for(it=xxx.end();it!=xxx.begin();--it){...}

can be illegal in case if you will manipulate iterator in loop body. 如果您要在循环体内操作迭代器,则可能是非法的。 Dereferencing xxx.end () can lead to segmentation fault. 取消引用xxx.end()可能导致分段错误。 In this case it's better to use reverse iterators: 在这种情况下,最好使用反向迭代器:

for(it=xxx.rbegin();it!=xxx.rend();++it){...}

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

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