Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

QMap contains() + value() - better way?



  • I've got the following bit of code:

    if (dockWindowConsoleMap.contains(windowName)) {
      font = dockWindowConsoleMap.value(windowName)->mUpperPane->mDisplayFont;
    

    It's tidy, it's safe, but my static analyser complains about the impossible case that I'm doing a null pointer dereference with value() because of the default-constructed argument. It's an impossible case because of the contains() check but it's not smart enough.

    I don't want to mark every time I use this pattern as a false positive in the static analyser - what's a better way to get a value from a QMap that's static-analysis friendly?


  • Qt Champions 2017

    You can try with QMap::find() and then QMap::Iterator::value() if the returned iterator isn't equal to QMap::end():

    QMap< ... >::Iterator element = dockWindowConsoleMap.find(windowName);
    if (element != dockWindowConsoleMap.end())
         font = element.value()->mUpperPane->mDisplayFont;
    


  • While @kshegunov suggests a correct efficency improvement, I doubt it will solve your problem as it's triggered by mUpperPane-> not what's on the left. Q_ASSERT should solve it though.

    const auto element = dockWindowConsoleMap.constFind(windowName);
    if (element != dockWindowConsoleMap.cend()){
    Q_ASSERT(element.value()->mUpperPane);
    font = element.value()->mUpperPane->mDisplayFont;
    }
    


  • I see. Thank you both for the responses.


Log in to reply