How do you manage a situation where objects inside a std::list need to move their position in, or even remove themselves from that list, while you are iterating over that list?
A complicated example follows.
You have an ordered list of objects.
list< Object* > objects ;
You have a loop that iterates over each
for( list< Object* >::iterator iter = objects.begin() ; iter != objects.end() ; ++iter )
{
// call "move()" on each
(*iter)->move() ;
}
Now here’s the catch. Object::move() sometimes reorders the list, the very list that we are iterating on with the loop above.
I’m not sure how to engineer this. How can I write and invoke a member function Object::move() that possibly re-orders the list every time you call it, and iterate over each element in the objects list, invoking Object::move() on each Object in the list?
Holistically.
Putting a member in the contained object that knows about and manipulates the container is almost universally a bad design choice. You want container->contained but not contained->container.
Your sorting routine is going to have to be just that, a sorting routine that uses whatever rules “move” would otherwise use to decide when to swap things around. You are basically ordering your list by some condition when you call “move” over all its elements, so you just change this idea of elements moving themselves to them being moved by something that knows how they need to be ordered. When you do this of course that condition can be different for different client needs.