mardi 29 juin 2021

Can map::find and iterator::second be used in one condition

I have such a piece of code:

std::map<int, int> mp;
// do something
auto itor = mp.find(some_value);
if (itor != mp.end() && itor->second == some_other_value) {
    // do something
}

I'm worrying about which expression would be evaluated first, itor != mp.end() or itor->second == some_other_value?

If the second one is evaluated firstly (because of some compiler-optimization maybe?), it might get an undefined behavior because itor == mp.end() may be true.

Should I worry about this issue so that I have to code like this:

if (itor != mp.end) {
    if (itor->second == some_other_value) {
        // do something
    }
}

Aucun commentaire:

Enregistrer un commentaire