C++ 列表迭代器不可解引用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2667574/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
List iterator not dereferencable?
提问by Roderick
I get the error "list iterator not dereferencable" when using the following code:
使用以下代码时出现错误“list iterator not dereferencable”:
bool done = false;
while (!_list_of_messages.empty() && !done) {
// request the next message to create a frame
// DEBUG ERROR WHEN NEXT LINE IS EXECUTED:
Counted_message_reader reader = *(_list_of_messages.begin());
if (reader.has_more_data()) {
_list_of_frames.push_back(new Dlp_data_frame(reader, _send_compressed_frames));
done = true;
} else {
_list_of_messages.pop_front();
}
}
(The line beginning with "Counted_message_reader..." is the one giving the problem)
(以“Counted_message_reader...”开头的那一行是问题所在)
Note that the error doesn't always occur but seemingly at random times (usually when there's lots of buffered data).
请注意,错误并不总是发生,但似乎是随机发生的(通常是在有大量缓冲数据时)。
_list_of_messages
is declared as follows:
_list_of_messages
声明如下:
std::list<Counted_message_reader> _list_of_messages;
In the surrounding code we could do pop_front
, push_front
and size
, empty
or end
checks on _list_of_messages
but no erase
calls.
在周围的代码中,我们可以执行pop_front
,push_front
和size
,empty
或end
检查_list_of_messages
但不erase
调用。
I've studied the STL documentation and can't see any glaring problems. Is there something wrong with the above code or do I have a memory leak somewhere?
我研究了 STL 文档,没有发现任何明显的问题。上面的代码有问题还是我在某处有内存泄漏?
Thanks! Appreciated!
谢谢!赞赏!
采纳答案by Adrian McCarthy
Could you have a race-condition?
你能有比赛条件吗?
If the list were empty, then I'd expect a problem when trying to dereference begin(), but you check for empty. Do you have another thread adding or removing items from list in parallel?
如果列表为空,那么在尝试取消引用 begin() 时,我预计会出现问题,但您会检查是否为空。您是否有另一个线程并行添加或删除列表中的项目?
Your code snippets works for me on VS 2008 (assuming I typedef Counted_message_reader
to int
).
您的代码片段在 VS 2008 上对我有用(假设我 typedefCounted_message_reader
为int
)。
回答by Nick Meyer
This assertion usually indicates some sort of memory corruption bug, such as when you've been manipulating a list from multiple threads or you've overwritten memory that stores the 'bookkeeping' for the list.
此断言通常表示某种内存损坏错误,例如当您从多个线程操作列表或覆盖存储列表“簿记”的内存时。
回答by kriss
For a list, iterators are invalidated when the element of the list that it refers to is erased. That's probably what happens, but I don't see it in your sample code. Wild pointer somewhere ? (not sure, I may be blind after of too much coding).
对于列表,当它引用的列表元素被擦除时,迭代器将失效。这可能就是发生的情况,但我在您的示例代码中没有看到它。某处的野生指针?(不确定,编码过多后我可能会失明)。