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 thecontains()
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? -
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 thecontains()
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?You can try with
QMap::find()
and thenQMap::Iterator::value()
if the returned iterator isn't equal toQMap::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; }