This question has been asked several times, but mine is a slightly different case. Let's say I have std :: vector observers that I notify when a specific event occurs:
void SomeClass::doThing() {
for (auto* o : mObservers) {
o->thingHappened();
}
}
What if in the implementation the thingHappenedobserver calls method in SomeClassto remove himself from the observers? What are some of the best ways to handle this?
One possibility is to make a copy mObserversbefore the for loop and use it instead, but an extra copy can be wasteful.
Another possibility is to delegate the changes to the array that will be launched after the loop finishes, possibly setting a lock (only logical) before the loop starts, and when this lock is set, methods that mutate the vector delegate themselves to be called after the loop is executed, when the lock is set to false (can be done with the lambdas vector ... rather cumbersome).
source
share