QPointingDevice: avoid double lookup in Private::pointById()

Use the newly-added try_emplace() function, to work around Qt's
associative container's broken insert() behavior (which is
equivalent to STL's insert_or_assign()), forcing either a double
lookup:

   auto it = c.find(key);  // lookup 1
   if (it == c.end())
      c.insert(key, ~~~);  // lookup 2

or the usual size-check trick:

    const auto oldSize = c.size();
    auto &e = c[key];
    if (c.size() != oldSize) {
        // newly inserted

onto any lookup-or-initialize-like code. try_emplace beats them
both in terms of efficiency and readability.

Pick-to: 6.3
Change-Id: I4c52d2f2d5175991db4931d29c688de125f5b032
Reviewed-by: Giuseppe D'Angelo <giuseppe.dangelo@kdab.com>
Reviewed-by: Shawn Rutledge <shawn.rutledge@qt.io>
This commit is contained in:
Marc Mutz 2022-01-07 09:10:51 +01:00
parent d4611ba3a5
commit 66a183298a

View File

@ -422,13 +422,12 @@ QPointingDevicePrivate::EventPointData *QPointingDevicePrivate::queryPointById(i
*/
QPointingDevicePrivate::EventPointData *QPointingDevicePrivate::pointById(int id) const
{
auto it = activePoints.find(id);
if (it == activePoints.end()) {
const auto [it, inserted] = activePoints.try_emplace(id);
if (inserted) {
Q_Q(const QPointingDevice);
QPointingDevicePrivate::EventPointData epd;
auto &epd = it.value();
QMutableEventPoint::setId(epd.eventPoint, id);
QMutableEventPoint::setDevice(epd.eventPoint, q);
return &activePoints.insert(id, epd).first.value();
}
return &it.value();
}