mardi 1 décembre 2020

C++: iterate over a list, calling a method that deletes its list member

Let us say a subscription can be represented as a string, perhaps a topic of interest.

My class has Subscribe() and Unsubscribe() methods taking these strings, and maintaining an unordered_set of the strings we're currently subscribed to.

The destructor, for convenience, will Desubscribe() from every topic you're currently subscribed to (which, let us say, is necessary for this system).

However the simple loop doesn't work because Unsubscribe() is deleting set items.

Note there are similar questions where the deletion is optional and perhaps done by the method in question. This question differs because the deletion is done by a different method.

So what is the clearest way to code this so that it works?

unordered_set<string> setsSubscribed;

MyClass::~MyClass() {
    while ( auto it: setsSubscribed )
        Unsubscribe( *it );
}

Aucun commentaire:

Enregistrer un commentaire