I've come across a problem like this more than once and I'd like to know the recommended approach(es) for dealing with it. Alternatively, I'd like to know if it has a name.
For concreteness, let's suppose we have a Colony object, one of whose members is a list of Organism objects. Organism objects have an Update method. Under certain conditions, the desired behavior upon calling Update is for the organism to "split itself in half" -- that is, to produce two new Organisms to be inserted into the collection, and then to have itself removed from the collection and destroyed.
To make things interesting, let's say the collection is ordered and we want the new Organisms inserted at the same point the old Organism previously occupied.
Moreover let's say we want to loop through the collection of Organisms calling Update on each, and we want to do this in such a way that Update does not get called on newly-created Organisms.
As a variant, perhaps the Organism wants to keep itself alive but to insert its offspring into the collection next to it.
I can think of a few ways to do this with various tradeoffs:
- Have Update return a list of Organisms, either itself or a list of new ones. Then have the loop calling Update construct a new collection from these and replace the old collection with it at the end.
- Pass Update some (callbacks / pointers / whatever) allowing it to insert items into the collection in such a way that the (iterator / loop index / whatever) gets moved past them.
- Have Update communicate its desire to insert new objects to the calling loop and have the calling code take care of the actual insertion.
Are there other reasonable ways to do this? Are there non-obvious advantages/disadvantages to them? Do they have names? Are there slick ways of doing them automatically?