简体   繁体   中英

c++ Iterator crashing while iterating over vector

I have a class Iformat which has virtual function operator() and each derived class implements this function.

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.

Constraints : operator() definition can not be declared otherwise to return an error type.
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; 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; 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;

  3. ensure, somehow, that the callback cannot modify the formatList_ , directly or indirectly; 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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