简体   繁体   English

C ++迭代器在向量上迭代时崩溃

[英]c++ Iterator crashing while iterating over vector

I have a class Iformat which has virtual function operator() and each derived class implements this function. 我有一个Iformat类,它具有虚函数operator(),每个派生类均实现此功能。

class myClass
{
    std::vector<IFormat*> formatList_;
public:
  void formatAll()
  {
    foreach(IFormat* format , formatList_)
    {
        (*format)();
    }
  }

};

The formatAll function is called on an object of myClass and then in the loop, the operator() function is deleting this myClass object itself which invoked the formatAll() function which is leading to a crash as the iterators are getting corrupted. myClass的对象上调用formatAll函数,然后在循环中, operator()函数删除此myClass对象本身,该对象本身调用了formatAll()函数,由于迭代器损坏,该函数导致崩溃。

Constraints : operator() definition can not be declared otherwise to return an error type. 约束 :否则无法声明operator()定义,否则将返回错误类型。
Also , can not use some indicator variable to break out of loop. 另外,不能使用某些指标变量来跳出循环。

Can somebody please suggest ways to handle the loop so that it does not crash by only changing the loop and iterators and following the constraints. 有人可以建议一些处理循环的方法,以免仅通过更改循环和迭代器并遵循约束条件而不会崩溃的情况。 Thanks 谢谢

Yeah, sometimes with a complicated chain of operations stemming from callbacks, this problem can surface. 是的,有时由于回调产生了一系列复杂的操作,这个问题可能会浮出水面。

You have a few options: 您有几种选择:

  1. copy the formatList_ within formatAll and iterate over the copy; 复制formatList_中的formatAll并遍历副本; you're only copying pointers but this may still be undesirable if the container is large, or if you are running this in a tight loop somewhere; 您只是在复制指针,但是如果容器很大,或者如果您在某个地方的紧密循环中运行它,这仍然可能是不可取的;

  2. in an event-driven framework, you can defer the execution of (*format)() until the start of the next application "tick", in this loop only adding it to some work queue; 在事件驱动的框架中,您可以将(*format)()的执行推迟到下一个应用程序“ tick”的开始,在此循环中仅将其添加到某些工作队列中; this is effectively the same as option #1, just a lot more complex, but if you do have such a framework it can slot in really nicely; 这实际上是相同的选项#1,只是很多更复杂的,但如果有这样一个框架,它可以真的很好槽;

  3. ensure, somehow, that the callback cannot modify the formatList_ , directly or indirectly; 确保以某种方式回调不能直接或间接修改formatList_ you might achieve this by prohibiting "add" or "remove" options, or forcing those to be deferred. 您可以通过禁止“添加”或“删除”选项或强制推迟使用这些选项来实现。

The "cleanest" approach is option #3 but, again, unless you are in an event-driven framework it can be clumsy to implement. 选项3是“最干净的”方法,但是同样,除非您处于事件驱动的框架中,否则实现起来可能很笨拙。

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

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