cleanup: replace Q_FOREACH and foreach by range base for

Q_FOREACH and foreach are anachronisms.

Range based for may cause a performance regression: it can
lead to a copy of shared containers (one reason why Qt's
COW containers are broken). However, as long as there is no
user noticeable delay, there is no point in analyzing each case.
And also no point in slapping an 'asConst' on every container
that is looped over.

Signed-off-by: Berthold Stoeger <bstoeger@mail.tuwien.ac.at>
This commit is contained in:
Berthold Stoeger 2024-03-16 16:50:43 +01:00 committed by bstoeger
parent 41cb916060
commit 5ac64ab2cd
16 changed files with 32 additions and 35 deletions

View file

@ -10,7 +10,7 @@ ColumnLimit: 0
ConstructorInitializerAllOnOneLineOrOnePerLine: true ConstructorInitializerAllOnOneLineOrOnePerLine: true
ConstructorInitializerIndentWidth: 8 ConstructorInitializerIndentWidth: 8
ContinuationIndentWidth: 8 ContinuationIndentWidth: 8
ForEachMacros: [ 'foreach', 'for_each_dc', 'for_each_relevant_dc', 'for_each_dive', 'for_each_line', 'Q_FOREACH' ] ForEachMacros: [ 'for_each_dc', 'for_each_relevant_dc', 'for_each_dive', 'for_each_line' ]
IndentFunctionDeclarationAfterType: false #personal taste, good for long methods IndentFunctionDeclarationAfterType: false #personal taste, good for long methods
IndentWidth: 8 IndentWidth: 8
MaxEmptyLinesToKeep: 2 MaxEmptyLinesToKeep: 2

View file

@ -156,7 +156,7 @@ void fill_computer_list()
descriptorLookup[QString(vendor).toLower() + QString(product).toLower()] = descriptor; descriptorLookup[QString(vendor).toLower() + QString(product).toLower()] = descriptor;
} }
dc_iterator_free(iterator); dc_iterator_free(iterator);
Q_FOREACH (QString vendor, vendorList) { for (const QString &vendor: vendorList) {
auto &l = productList[vendor]; auto &l = productList[vendor];
std::sort(l.begin(), l.end()); std::sort(l.begin(), l.end());
} }
@ -194,9 +194,9 @@ void show_computer_list()
{ {
unsigned int transportMask = get_supported_transports(NULL); unsigned int transportMask = get_supported_transports(NULL);
qDebug() << "Supported dive computers:"; qDebug() << "Supported dive computers:";
Q_FOREACH (QString vendor, vendorList) { for (const QString &vendor: vendorList) {
QString msg = vendor + ": "; QString msg = vendor + ": ";
Q_FOREACH (QString product, productList[vendor]) { for (const QString &product: productList[vendor]) {
dc_descriptor_t *descriptor = descriptorLookup[vendor.toLower() + product.toLower()]; dc_descriptor_t *descriptor = descriptorLookup[vendor.toLower() + product.toLower()];
unsigned int transport = dc_descriptor_get_transports(descriptor) & transportMask; unsigned int transport = dc_descriptor_get_transports(descriptor) & transportMask;
QString transportString = getTransportString(transport); QString transportString = getTransportString(transport);

View file

@ -47,7 +47,7 @@ int getCoordsFromGPXFile(struct dive_coords *coords, const QString &fileName)
if (nameCmp(gpxReader, "trkpt") == 0) { if (nameCmp(gpxReader, "trkpt") == 0) {
trkpt_found = true; trkpt_found = true;
line++; line++;
foreach (const QXmlStreamAttribute &attr, gpxReader.attributes()) { for (const QXmlStreamAttribute &attr: gpxReader.attributes()) {
if (attr.name().toString() == QLatin1String("lat")) if (attr.name().toString() == QLatin1String("lat"))
lat = attr.value().toString().toDouble(); lat = attr.value().toString().toDouble();
else if (attr.name().toString() == QLatin1String("lon")) else if (attr.name().toString() == QLatin1String("lon"))

View file

@ -308,7 +308,7 @@ dc_status_t BLEObject::write(const void *data, size_t size, size_t *actual)
} while (!receivedPackets.isEmpty()); } while (!receivedPackets.isEmpty());
} }
foreach (const QLowEnergyCharacteristic &c, preferredService()->characteristics()) { for (const QLowEnergyCharacteristic &c: preferredService()->characteristics()) {
if (!is_write_characteristic(c)) if (!is_write_characteristic(c))
continue; continue;
@ -398,7 +398,7 @@ dc_status_t BLEObject::read(void *data, size_t size, size_t *actual)
dc_status_t BLEObject::select_preferred_service(void) dc_status_t BLEObject::select_preferred_service(void)
{ {
// Wait for each service to finish discovering // Wait for each service to finish discovering
foreach (const QLowEnergyService *s, services) { for (const QLowEnergyService *s: services) {
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
WAITFOR(s->state() != QLowEnergyService::RemoteServiceDiscovering, BLE_TIMEOUT); WAITFOR(s->state() != QLowEnergyService::RemoteServiceDiscovering, BLE_TIMEOUT);
if (s->state() == QLowEnergyService::RemoteServiceDiscovering) if (s->state() == QLowEnergyService::RemoteServiceDiscovering)
@ -410,19 +410,19 @@ dc_status_t BLEObject::select_preferred_service(void)
} }
// Print out the services for debugging // Print out the services for debugging
foreach (const QLowEnergyService *s, services) { for (const QLowEnergyService *s: services) {
qDebug() << "Found service" << s->serviceUuid() << s->serviceName(); qDebug() << "Found service" << s->serviceUuid() << s->serviceName();
foreach (const QLowEnergyCharacteristic &c, s->characteristics()) { for (const QLowEnergyCharacteristic &c: s->characteristics()) {
qDebug() << " c:" << c.uuid(); qDebug() << " c:" << c.uuid();
foreach (const QLowEnergyDescriptor &d, c.descriptors()) for (const QLowEnergyDescriptor &d: c.descriptors())
qDebug() << " d:" << d.uuid(); qDebug() << " d:" << d.uuid();
} }
} }
// Pick the preferred one // Pick the preferred one
foreach (QLowEnergyService *s, services) { for (QLowEnergyService *s: services) {
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
if (s->state() != QLowEnergyService::RemoteServiceDiscovered) if (s->state() != QLowEnergyService::RemoteServiceDiscovered)
#else #else
@ -434,7 +434,7 @@ dc_status_t BLEObject::select_preferred_service(void)
bool haswrite = false; bool haswrite = false;
QBluetoothUuid uuid = s->serviceUuid(); QBluetoothUuid uuid = s->serviceUuid();
foreach (const QLowEnergyCharacteristic &c, s->characteristics()) { for (const QLowEnergyCharacteristic &c: s->characteristics()) {
hasread |= is_read_characteristic(c); hasread |= is_read_characteristic(c);
haswrite |= is_write_characteristic(c); haswrite |= is_write_characteristic(c);
} }
@ -615,9 +615,8 @@ dc_status_t qt_ble_open(void **io, dc_context_t *, const char *devaddr, device_d
// Finish discovering the services, then add all those services and discover their characteristics. // Finish discovering the services, then add all those services and discover their characteristics.
ble->connect(controller, &QLowEnergyController::discoveryFinished, [=] { ble->connect(controller, &QLowEnergyController::discoveryFinished, [=] {
qDebug() << "finished service discovery, start discovering characteristics"; qDebug() << "finished service discovery, start discovering characteristics";
foreach(QBluetoothUuid s, controller->services()) { for (QBluetoothUuid s: controller->services())
ble->addService(s); ble->addService(s);
}
}); });
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
ble->connect(controller, &QLowEnergyController::errorOccurred, [=](QLowEnergyController::Error newError) { ble->connect(controller, &QLowEnergyController::errorOccurred, [=](QLowEnergyController::Error newError) {

View file

@ -1176,7 +1176,7 @@ QStringList mediaExtensionFilters()
QStringList imageExtensionFilters() QStringList imageExtensionFilters()
{ {
QStringList filters; QStringList filters;
foreach (const QString &format, QImageReader::supportedImageFormats()) for (QString format: QImageReader::supportedImageFormats())
filters.append("*." + format); filters.append("*." + format);
return filters; return filters;
} }

View file

@ -486,7 +486,7 @@ void DiveListView::selectionChanged(const QItemSelection &selected, const QItemS
QItemSelection newSelected = selected.size() ? selected : selectionModel()->selection(); QItemSelection newSelected = selected.size() ? selected : selectionModel()->selection();
std::vector<dive *> addToSelection, removeFromSelection; std::vector<dive *> addToSelection, removeFromSelection;
Q_FOREACH (const QModelIndex &index, newDeselected.indexes()) { for (const QModelIndex &index: newDeselected.indexes()) {
if (index.column() != 0) if (index.column() != 0)
continue; continue;
const QAbstractItemModel *model = index.model(); const QAbstractItemModel *model = index.model();
@ -499,7 +499,7 @@ void DiveListView::selectionChanged(const QItemSelection &selected, const QItemS
removeFromSelection.push_back(trip->dives.dives[i]); removeFromSelection.push_back(trip->dives.dives[i]);
} }
} }
Q_FOREACH (const QModelIndex &index, newSelected.indexes()) { for (const QModelIndex &index: newSelected.indexes()) {
if (index.column() != 0) if (index.column() != 0)
continue; continue;

View file

@ -495,7 +495,7 @@ void DiveLogImportDialog::loadFileContents(int value, whatChanged triggeredBy)
firstLine = f.readLine().trimmed(); firstLine = f.readLine().trimmed();
currColumns = firstLine.split(';'); currColumns = firstLine.split(';');
Q_FOREACH (QString columnText, currColumns) { for (const QString &columnText: currColumns) {
if (columnText == "Time") { if (columnText == "Time") {
headers.append("Sample time"); headers.append("Sample time");
} else if (columnText == "Depth") { } else if (columnText == "Depth") {
@ -613,7 +613,7 @@ void DiveLogImportDialog::loadFileContents(int value, whatChanged triggeredBy)
if (line.length() > 0) if (line.length() > 0)
columns = line.split(separator); columns = line.split(separator);
// now try and guess the columns // now try and guess the columns
Q_FOREACH (QString columnText, currColumns) { for (QString columnText: currColumns) {
count++; count++;
/* /*
* We have to skip the conversion of 2 to for APD Log * We have to skip the conversion of 2 to for APD Log

View file

@ -99,7 +99,7 @@ void GroupedLineEdit::addColor(QColor color)
QStringList GroupedLineEdit::getBlockStringList() QStringList GroupedLineEdit::getBlockStringList()
{ {
QStringList retList; QStringList retList;
foreach (const Private::Block &block, d->blocks) for (const Private::Block &block: d->blocks)
retList.append(block.text); retList.append(block.text);
return retList; return retList;
} }
@ -179,7 +179,7 @@ void GroupedLineEdit::paintEvent(QPaintEvent *e)
QVectorIterator<QColor> i(d->colors); QVectorIterator<QColor> i(d->colors);
i.toFront(); i.toFront();
foreach (const Private::Block &block, d->blocks) { for (const Private::Block &block: d->blocks) {
qreal start_x = line.cursorToX(block.start, QTextLine::Leading); qreal start_x = line.cursorToX(block.start, QTextLine::Leading);
qreal end_x = line.cursorToX(block.end-1, QTextLine::Trailing); qreal end_x = line.cursorToX(block.end-1, QTextLine::Trailing);

View file

@ -111,7 +111,7 @@ void KMessageWidgetPrivate::createLayout()
qDeleteAll(buttons); qDeleteAll(buttons);
buttons.clear(); buttons.clear();
Q_FOREACH (QAction *action, q->actions()) { for (QAction *action: q->actions()) {
QToolButton *button = new QToolButton(content); QToolButton *button = new QToolButton(content);
button->setDefaultAction(action); button->setDefaultAction(action);
button->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); button->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
@ -131,7 +131,7 @@ void KMessageWidgetPrivate::createLayout()
QHBoxLayout *buttonLayout = new QHBoxLayout; QHBoxLayout *buttonLayout = new QHBoxLayout;
buttonLayout->addStretch(); buttonLayout->addStretch();
Q_FOREACH (QToolButton *button, buttons) { for (QToolButton *button: buttons) {
// For some reason, calling show() is necessary if wordwrap is true, // For some reason, calling show() is necessary if wordwrap is true,
// otherwise the buttons do not show up. It is not needed if // otherwise the buttons do not show up. It is not needed if
// wordwrap is false. // wordwrap is false.
@ -145,9 +145,8 @@ void KMessageWidgetPrivate::createLayout()
layout->addWidget(iconLabel); layout->addWidget(iconLabel);
layout->addWidget(textLabel); layout->addWidget(textLabel);
Q_FOREACH (QToolButton *button, buttons) { for (QToolButton *button: buttons)
layout->addWidget(button); layout->addWidget(button);
}
layout->addWidget(closeButton); layout->addWidget(closeButton);
}; };

View file

@ -379,7 +379,7 @@ void MainWindow::on_actionOpen_triggered()
QStringList cleanFilenames; QStringList cleanFilenames;
QRegularExpression reg(".*\\[[^]]+]\\.ssrf", QRegularExpression::CaseInsensitiveOption); QRegularExpression reg(".*\\[[^]]+]\\.ssrf", QRegularExpression::CaseInsensitiveOption);
Q_FOREACH (QString filename, filenames) { for (QString filename: filenames) {
if (reg.match(filename).hasMatch()) if (reg.match(filename).hasMatch())
filename.remove(QRegularExpression("\\.ssrf$", QRegularExpression::CaseInsensitiveOption)); filename.remove(QRegularExpression("\\.ssrf$", QRegularExpression::CaseInsensitiveOption));
cleanFilenames << filename; cleanFilenames << filename;
@ -1071,7 +1071,7 @@ void MainWindow::loadRecentFiles()
recentFiles.clear(); recentFiles.clear();
QSettings s; QSettings s;
s.beginGroup("Recent_Files"); s.beginGroup("Recent_Files");
foreach (const QString &key, s.childKeys()) { for (const QString &key: s.childKeys()) {
// TODO Sorting only correct up to 9 entries. Currently, only 4 used, so no problem. // TODO Sorting only correct up to 9 entries. Currently, only 4 used, so no problem.
if (!key.startsWith("File_")) if (!key.startsWith("File_"))
continue; continue;

View file

@ -27,7 +27,7 @@ PreferencesLanguage::PreferencesLanguage() : AbstractPreferencesWidget(tr("Langu
dateFormatShortMap.insert("MM/dd/yyyy", "M/d/yy"); dateFormatShortMap.insert("MM/dd/yyyy", "M/d/yy");
dateFormatShortMap.insert("dd.MM.yyyy", "d.M.yy"); dateFormatShortMap.insert("dd.MM.yyyy", "d.M.yy");
dateFormatShortMap.insert("yyyy-MM-dd", "yy-M-d"); dateFormatShortMap.insert("yyyy-MM-dd", "yy-M-d");
foreach (QString format, dateFormatShortMap.keys()) for (const QString &format: dateFormatShortMap.keys())
ui->dateFormatEntry->addItem(format); ui->dateFormatEntry->addItem(format);
ui->dateFormatEntry->completer()->setCaseSensitivity(Qt::CaseSensitive); ui->dateFormatEntry->completer()->setCaseSensitivity(Qt::CaseSensitive);
connect(ui->dateFormatEntry, &QComboBox::currentTextChanged, connect(ui->dateFormatEntry, &QComboBox::currentTextChanged,

View file

@ -55,7 +55,7 @@ void set_bundled_templates_as_read_only()
listStats[i] = stats + QDir::separator() + listStats.at(i); listStats[i] = stats + QDir::separator() + listStats.at(i);
list += listStats; list += listStats;
foreach (const QString& f, list) for (const QString &f: list)
QFile::setPermissions(pathUser + QDir::separator() + f, QFileDevice::ReadOwner | QFileDevice::ReadUser); QFile::setPermissions(pathUser + QDir::separator() + f, QFileDevice::ReadOwner | QFileDevice::ReadUser);
} }

View file

@ -2365,13 +2365,13 @@ QStringList QMLManager::cloudCacheList() const
QDir localCacheDir(QString("%1/cloudstorage/").arg(system_default_directory())); QDir localCacheDir(QString("%1/cloudstorage/").arg(system_default_directory()));
QStringList dirs = localCacheDir.entryList(); QStringList dirs = localCacheDir.entryList();
QStringList result; QStringList result;
foreach(QString dir, dirs) { for (const QString &dir: dirs) {
QString originsDir = QString("%1/cloudstorage/%2/.git/refs/remotes/origin/").arg(system_default_directory()).arg(dir); QString originsDir = QString("%1/cloudstorage/%2/.git/refs/remotes/origin/").arg(system_default_directory()).arg(dir);
QDir remote(originsDir); QDir remote(originsDir);
if (dir == "localrepo") { if (dir == "localrepo") {
result << QString("localrepo[master]"); result << QString("localrepo[master]");
} else { } else {
foreach(QString branch, remote.entryList().filter(QRegularExpression("...+"))) for (const QString &branch: remote.entryList().filter(QRegularExpression("...+")))
result << QString("%1[%2]").arg(dir).arg(branch); result << QString("%1[%2]").arg(dir).arg(branch);
} }
} }

View file

@ -216,8 +216,7 @@ void MapLocationModel::setSelected(const QVector<dive_site *> &divesites)
MapLocation *MapLocationModel::getMapLocation(const struct dive_site *ds) MapLocation *MapLocationModel::getMapLocation(const struct dive_site *ds)
{ {
MapLocation *location; for (MapLocation *location: m_mapLocations) {
foreach(location, m_mapLocations) {
if (ds == location->divesite) if (ds == location->divesite)
return location; return location;
} }

View file

@ -64,7 +64,7 @@ LanguageModel *LanguageModel::instance()
LanguageModel::LanguageModel(QObject *parent) : QAbstractListModel(parent) LanguageModel::LanguageModel(QObject *parent) : QAbstractListModel(parent)
{ {
QDir d(getSubsurfaceDataPath("translations")); QDir d(getSubsurfaceDataPath("translations"));
Q_FOREACH (const QString &s, d.entryList()) { for (const QString &s: d.entryList()) {
if (s.startsWith("subsurface_") && s.endsWith(".qm")) { if (s.startsWith("subsurface_") && s.endsWith(".qm")) {
languages.push_back((s == "subsurface_source.qm") ? "English" : s); languages.push_back((s == "subsurface_source.qm") ? "English" : s);
} }

View file

@ -3,7 +3,7 @@
my $input = $ARGV[0]; my $input = $ARGV[0];
my $source = `clang-format $input`; my $source = `clang-format $input`;
# for_each_dive (...) and Q_FOREACH and friends... # for_each_dive (...) and friends...
$source =~ s/(?:\G|^)(.*each.*\(.*) \* (\S.*\))$/$1 *$2/img; # if a variable is declared in the argument, '*' is an indicator for a pointer, not arithmatic $source =~ s/(?:\G|^)(.*each.*\(.*) \* (\S.*\))$/$1 *$2/img; # if a variable is declared in the argument, '*' is an indicator for a pointer, not arithmatic
$source =~ s/(?:\G|^)(.*each.*\(.*) \& (\S.*\))$/$1 &$2/img; # if a variable is declared in the argument, '&' is an indicator for a reference, not bit logic $source =~ s/(?:\G|^)(.*each.*\(.*) \& (\S.*\))$/$1 &$2/img; # if a variable is declared in the argument, '&' is an indicator for a reference, not bit logic
$source =~ s/(?:\G|^)(.*each[^\s(]*)\s*(\(.*)$/$1 $2/img; # we want exactly one space between keyword and opening parenthesis '(' $source =~ s/(?:\G|^)(.*each[^\s(]*)\s*(\(.*)$/$1 $2/img; # we want exactly one space between keyword and opening parenthesis '('