summaryrefslogtreecommitdiff
path: root/src/mongo
diff options
context:
space:
mode:
authorTrevor Guidry <trevor.guidry@mongodb.com>2022-09-16 19:00:42 +0000
committerEvergreen Agent <no-reply@evergreen.mongodb.com>2022-09-20 18:00:27 +0000
commitbc998019c79c83db140317c3e59761fdd12a8c5f (patch)
tree2d6ce6aafdf155f07fd403c9fff7454c86a8f09f /src/mongo
parent03bf5f2dff26f3d5c3ca4687c565c3c764bcc013 (diff)
downloadmongo-bc998019c79c83db140317c3e59761fdd12a8c5f.tar.gz
SERVER-69581 add performance-for-range-copy check to clang-tidy
Diffstat (limited to 'src/mongo')
-rw-r--r--src/mongo/client/replica_set_change_notifier.cpp8
-rw-r--r--src/mongo/client/replica_set_monitor_manager.cpp2
-rw-r--r--src/mongo/client/sdam/sdam_json_test_runner.cpp4
-rw-r--r--src/mongo/client/sdam/server_selection_json_test_runner.cpp2
-rw-r--r--src/mongo/client/sdam/topology_description.cpp4
-rw-r--r--src/mongo/client/sdam/topology_description_test.cpp4
-rw-r--r--src/mongo/client/sdam/topology_listener.cpp2
-rw-r--r--src/mongo/client/sdam/topology_manager_test.cpp2
-rw-r--r--src/mongo/client/sdam/topology_state_machine_test.cpp6
-rw-r--r--src/mongo/client/server_discovery_monitor.cpp2
-rw-r--r--src/mongo/client/streamable_replica_set_monitor.cpp4
-rw-r--r--src/mongo/crypto/fle_crypto.cpp2
-rw-r--r--src/mongo/db/active_index_builds.cpp4
-rw-r--r--src/mongo/db/catalog/catalog_control.cpp2
-rw-r--r--src/mongo/db/catalog/index_builds_manager_test.cpp2
-rw-r--r--src/mongo/db/catalog/index_catalog_impl.cpp2
-rw-r--r--src/mongo/db/catalog/index_consistency.cpp2
-rw-r--r--src/mongo/db/catalog/views_for_database.cpp2
-rw-r--r--src/mongo/db/commands/command_mirroring_test.cpp4
-rw-r--r--src/mongo/db/commands/dbhash.cpp6
-rw-r--r--src/mongo/db/curop.cpp2
-rw-r--r--src/mongo/db/exec/sbe/sbe_hash_join_test.cpp2
-rw-r--r--src/mongo/db/exec/sbe/stages/column_scan.cpp4
-rw-r--r--src/mongo/db/exec/sbe/util/stage_results_printer.cpp4
-rw-r--r--src/mongo/db/exec/sbe/values/column_store_encoder_test.cpp2
-rw-r--r--src/mongo/db/geo/r2_region_coverer_test.cpp12
-rw-r--r--src/mongo/db/index/column_key_generator_test.cpp2
-rw-r--r--src/mongo/db/index/index_access_method.cpp2
-rw-r--r--src/mongo/db/index_builds_coordinator.cpp14
-rw-r--r--src/mongo/db/index_builds_coordinator_mongod_test.cpp2
-rw-r--r--src/mongo/db/matcher/expression_algo.cpp2
-rw-r--r--src/mongo/db/matcher/expression_algo_test.cpp2
-rw-r--r--src/mongo/db/matcher/expression_path.h2
-rw-r--r--src/mongo/db/matcher/rewrite_expr.cpp2
-rw-r--r--src/mongo/db/mirror_maestro.cpp2
-rw-r--r--src/mongo/db/mirroring_sampler_test.cpp6
-rw-r--r--src/mongo/db/op_observer/op_observer_impl.cpp6
-rw-r--r--src/mongo/db/ops/parsed_update_array_filters.cpp2
-rw-r--r--src/mongo/db/pipeline/document_source_densify.cpp2
-rw-r--r--src/mongo/db/pipeline/document_source_graph_lookup.cpp2
-rw-r--r--src/mongo/db/pipeline/document_source_group.cpp2
-rw-r--r--src/mongo/db/pipeline/document_source_internal_unpack_bucket_test/optimize_lastpoint_test.cpp4
-rw-r--r--src/mongo/db/pipeline/document_source_lookup.cpp2
-rw-r--r--src/mongo/db/pipeline/document_source_merge.cpp2
-rw-r--r--src/mongo/db/pipeline/document_source_queue.cpp2
-rw-r--r--src/mongo/db/pipeline/document_source_set_window_fields.cpp2
-rw-r--r--src/mongo/db/pipeline/expression.h2
-rw-r--r--src/mongo/db/pipeline/expression_bm.cpp2
-rw-r--r--src/mongo/db/pipeline/expression_convert_test.cpp4
-rw-r--r--src/mongo/db/pipeline/expression_date_test.cpp4
-rw-r--r--src/mongo/db/pipeline/expression_test.cpp2
-rw-r--r--src/mongo/db/pipeline/pipeline_test.cpp2
-rw-r--r--src/mongo/db/pipeline/sharded_agg_helpers.cpp2
-rw-r--r--src/mongo/db/pipeline/window_function/window_function_add_to_set_test.cpp2
-rw-r--r--src/mongo/db/pipeline/window_function/window_function_covariance.cpp2
-rw-r--r--src/mongo/db/pipeline/window_function/window_function_covariance_test.cpp2
-rw-r--r--src/mongo/db/pipeline/window_function/window_function_integral_test.cpp2
-rw-r--r--src/mongo/db/pipeline/window_function/window_function_push_test.cpp2
-rw-r--r--src/mongo/db/process_health/state_machine.h2
-rw-r--r--src/mongo/db/query/index_bounds_builder_eq_null_test.cpp14
-rw-r--r--src/mongo/db/query/query_planner_geo_test.cpp8
-rw-r--r--src/mongo/db/query/sbe_stage_builder_accumulator_test.cpp4
-rw-r--r--src/mongo/db/repl/idempotency_document_structure.cpp8
-rw-r--r--src/mongo/db/repl/idempotency_document_structure_test.cpp2
-rw-r--r--src/mongo/db/repl/idempotency_test_fixture.cpp2
-rw-r--r--src/mongo/db/repl/oplog.cpp2
-rw-r--r--src/mongo/db/repl/oplog_applier_impl.cpp4
-rw-r--r--src/mongo/db/repl/oplog_applier_test.cpp2
-rw-r--r--src/mongo/db/repl/repl_set_config_checks.cpp4
-rw-r--r--src/mongo/db/repl/replication_consistency_markers_impl.cpp3
-rw-r--r--src/mongo/db/repl/replication_coordinator_impl_heartbeat.cpp2
-rw-r--r--src/mongo/db/repl/replication_coordinator_impl_heartbeat_v1_test.cpp2
-rw-r--r--src/mongo/db/repl/replication_coordinator_impl_test.cpp6
-rw-r--r--src/mongo/db/repl/rs_rollback.cpp2
-rw-r--r--src/mongo/db/repl/tenant_migration_recipient_service_test.cpp6
-rw-r--r--src/mongo/db/repl/tenant_oplog_batcher_test.cpp2
-rw-r--r--src/mongo/db/s/config/initial_split_policy.cpp2
-rw-r--r--src/mongo/db/s/config/sharding_catalog_manager_config_initialization_test.cpp2
-rw-r--r--src/mongo/db/s/config/sharding_catalog_manager_remove_shard_test.cpp2
-rw-r--r--src/mongo/db/s/migration_chunk_cloner_source_legacy_test.cpp2
-rw-r--r--src/mongo/db/s/resharding/resharding_util.cpp4
-rw-r--r--src/mongo/db/s/session_catalog_migration_source_test.cpp12
-rw-r--r--src/mongo/db/s/sharding_ddl_util.cpp6
-rw-r--r--src/mongo/db/s/shardsvr_abort_reshard_collection_command.cpp2
-rw-r--r--src/mongo/db/s/shardsvr_commit_reshard_collection_command.cpp2
-rw-r--r--src/mongo/db/serverless/shard_split_donor_service_test.cpp2
-rw-r--r--src/mongo/db/serverless/shard_split_test_utils.cpp4
-rw-r--r--src/mongo/db/serverless/shard_split_utils.cpp2
-rw-r--r--src/mongo/db/storage/key_string_bm.cpp2
-rw-r--r--src/mongo/db/storage/key_string_test.cpp4
-rw-r--r--src/mongo/db/storage/storage_engine_impl.cpp4
-rw-r--r--src/mongo/db/storage/wiredtiger/wiredtiger_util.cpp2
-rw-r--r--src/mongo/db/timeseries/bucket_catalog_helpers_test.cpp2
-rw-r--r--src/mongo/dbtests/query_stage_batched_delete.cpp2
-rw-r--r--src/mongo/dbtests/query_stage_collscan.cpp2
-rw-r--r--src/mongo/dbtests/query_stage_trial.cpp8
-rw-r--r--src/mongo/dbtests/querytests.cpp2
-rw-r--r--src/mongo/executor/task_executor_cursor_integration_test.cpp2
-rw-r--r--src/mongo/executor/task_executor_test_common.cpp2
-rw-r--r--src/mongo/logv2/redaction_test.cpp8
-rw-r--r--src/mongo/rpc/metadata_test.cpp4
-rw-r--r--src/mongo/s/multi_statement_transaction_requests_sender.cpp2
-rw-r--r--src/mongo/s/transaction_router_test.cpp8
-rw-r--r--src/mongo/shell/shell_options.cpp2
-rw-r--r--src/mongo/unittest/unittest.cpp2
-rw-r--r--src/mongo/unittest/unittest_main.cpp2
-rw-r--r--src/mongo/util/concurrency/thread_pool_test_common.cpp2
-rw-r--r--src/mongo/util/pcre_test.cpp2
108 files changed, 182 insertions, 181 deletions
diff --git a/src/mongo/client/replica_set_change_notifier.cpp b/src/mongo/client/replica_set_change_notifier.cpp
index 3f76e6c1a20..6f788b88418 100644
--- a/src/mongo/client/replica_set_change_notifier.cpp
+++ b/src/mongo/client/replica_set_change_notifier.cpp
@@ -62,7 +62,7 @@ void ReplicaSetChangeNotifier::onFoundSet(const std::string& name) noexcept {
auto listeners = _listeners;
lk.unlock();
- for (auto listener : listeners) {
+ for (const auto& listener : listeners) {
if (auto l = listener.lock()) {
l->onFoundSet(name);
}
@@ -93,7 +93,7 @@ void ReplicaSetChangeNotifier::onPossibleSet(ConnectionString connectionString)
auto listeners = _listeners;
lk.unlock();
- for (auto listener : listeners) {
+ for (const auto& listener : listeners) {
if (auto l = listener.lock()) {
l->onPossibleSet(state);
}
@@ -127,7 +127,7 @@ void ReplicaSetChangeNotifier::onConfirmedSet(ConnectionString connectionString,
auto listeners = _listeners;
lk.unlock();
- for (auto listener : listeners) {
+ for (const auto& listener : listeners) {
if (auto l = listener.lock()) {
l->onConfirmedSet(state);
}
@@ -154,7 +154,7 @@ void ReplicaSetChangeNotifier::onDroppedSet(const std::string& name) noexcept {
auto listeners = _listeners;
lk.unlock();
- for (auto listener : listeners) {
+ for (const auto& listener : listeners) {
if (auto l = listener.lock()) {
l->onDroppedSet(name);
}
diff --git a/src/mongo/client/replica_set_monitor_manager.cpp b/src/mongo/client/replica_set_monitor_manager.cpp
index 81fbcc826de..09394f8d2e6 100644
--- a/src/mongo/client/replica_set_monitor_manager.cpp
+++ b/src/mongo/client/replica_set_monitor_manager.cpp
@@ -212,7 +212,7 @@ shared_ptr<ReplicaSetMonitor> ReplicaSetMonitorManager::getMonitorForHost(const
stdx::lock_guard<Latch> lk(_mutex);
- for (auto entry : _monitors) {
+ for (const auto& entry : _monitors) {
auto monitor = entry.second.lock();
if (monitor && monitor->contains(host)) {
return monitor;
diff --git a/src/mongo/client/sdam/sdam_json_test_runner.cpp b/src/mongo/client/sdam/sdam_json_test_runner.cpp
index 1cc4ca3d60c..1e9bd207ba4 100644
--- a/src/mongo/client/sdam/sdam_json_test_runner.cpp
+++ b/src/mongo/client/sdam/sdam_json_test_runner.cpp
@@ -112,7 +112,7 @@ public:
PhaseResult execute(TopologyManager& topology) const {
PhaseResult testResult{{}, _phaseNum};
- for (auto response : _isMasterResponses) {
+ for (const auto& response : _isMasterResponses) {
auto descriptionStr =
(response.getResponse()) ? response.getResponse()->toString() : "[ Network Error ]";
LOGV2(20202,
@@ -542,7 +542,7 @@ public:
std::vector<JsonTestCase::TestCaseResult> runTests() {
std::vector<JsonTestCase::TestCaseResult> results;
const auto testFiles = getTestFiles();
- for (auto jsonTest : testFiles) {
+ for (const auto& jsonTest : testFiles) {
auto testCase = JsonTestCase(jsonTest);
try {
LOGV2(20208, "### Executing Test Case ###", "test"_attr = testCase.Name());
diff --git a/src/mongo/client/sdam/server_selection_json_test_runner.cpp b/src/mongo/client/sdam/server_selection_json_test_runner.cpp
index 8005cf8a901..356db02e575 100644
--- a/src/mongo/client/sdam/server_selection_json_test_runner.cpp
+++ b/src/mongo/client/sdam/server_selection_json_test_runner.cpp
@@ -466,7 +466,7 @@ public:
std::vector<JsonTestCase::TestCaseResult> runTests() {
std::vector<JsonTestCase::TestCaseResult> results;
const auto testFiles = getTestFiles();
- for (auto jsonTest : testFiles) {
+ for (const auto& jsonTest : testFiles) {
int restoreHeartBeatFrequencyMs = sdamHeartBeatFrequencyMs;
std::unique_ptr<JsonTestCase> testCase;
diff --git a/src/mongo/client/sdam/topology_description.cpp b/src/mongo/client/sdam/topology_description.cpp
index 5552aeacb94..31d3a3e0760 100644
--- a/src/mongo/client/sdam/topology_description.cpp
+++ b/src/mongo/client/sdam/topology_description.cpp
@@ -258,7 +258,7 @@ void TopologyDescription::calculateLogicalSessionTimeout() {
bool hasDataBearingServer = false;
invariant(_servers.size() > 0);
- for (auto description : _servers) {
+ for (const auto& description : _servers) {
if (!description->isDataBearingServer()) {
continue;
}
@@ -282,7 +282,7 @@ BSONObj TopologyDescription::toBSON() {
bson << "topologyType" << mongo::sdam::toString(_type);
BSONObjBuilder bsonServers;
- for (auto server : this->getServers()) {
+ for (const auto& server : this->getServers()) {
bsonServers << server->getAddress().toString() << server->toBson();
}
bson.append("servers", bsonServers.obj());
diff --git a/src/mongo/client/sdam/topology_description_test.cpp b/src/mongo/client/sdam/topology_description_test.cpp
index 2448ac374dd..a401b870612 100644
--- a/src/mongo/client/sdam/topology_description_test.cpp
+++ b/src/mongo/client/sdam/topology_description_test.cpp
@@ -254,7 +254,7 @@ TEST_F(TopologyDescriptionTestFixture, ShouldSetLogicalSessionTimeoutToMinOfAllS
return newInstanceBuilder.instance();
});
- for (auto description : serverDescriptionsWithTimeouts) {
+ for (const auto& description : serverDescriptionsWithTimeouts) {
topologyDescription->installServerDescription(description);
}
@@ -289,7 +289,7 @@ TEST_F(TopologyDescriptionTestFixture,
return newInstance;
});
- for (auto description : serverDescriptionsWithTimeouts) {
+ for (const auto& description : serverDescriptionsWithTimeouts) {
topologyDescription->installServerDescription(description);
}
diff --git a/src/mongo/client/sdam/topology_listener.cpp b/src/mongo/client/sdam/topology_listener.cpp
index 3eb730e439c..215b64d2871 100644
--- a/src/mongo/client/sdam/topology_listener.cpp
+++ b/src/mongo/client/sdam/topology_listener.cpp
@@ -218,7 +218,7 @@ void TopologyEventsPublisher::_nextDelivery() {
}
// send to the listeners outside of the lock.
- for (auto listener : listeners) {
+ for (const auto& listener : listeners) {
// The copy logic above guaranteed that only non-empty elements are in the vector.
_sendEvent(listener.get(), *nextEvent);
}
diff --git a/src/mongo/client/sdam/topology_manager_test.cpp b/src/mongo/client/sdam/topology_manager_test.cpp
index ecfeb371384..e084e6072e5 100644
--- a/src/mongo/client/sdam/topology_manager_test.cpp
+++ b/src/mongo/client/sdam/topology_manager_test.cpp
@@ -106,7 +106,7 @@ TEST_F(TopologyManagerTestFixture,
ShouldUpdateServerDescriptionsTopologyDescriptionPtrWhenTopologyDescriptionIsInstalled) {
auto checkServerTopologyDescriptionMatches = [](TopologyDescriptionPtr topologyDescription) {
auto rawTopologyDescPtr = topologyDescription.get();
- for (auto server : topologyDescription->getServers()) {
+ for (const auto& server : topologyDescription->getServers()) {
auto rawServerTopologyDescPtr = (*server->getTopologyDescription()).get();
ASSERT(server->getTopologyDescription());
ASSERT(rawServerTopologyDescPtr == rawTopologyDescPtr);
diff --git a/src/mongo/client/sdam/topology_state_machine_test.cpp b/src/mongo/client/sdam/topology_state_machine_test.cpp
index c549286eb70..0481b896e1e 100644
--- a/src/mongo/client/sdam/topology_state_machine_test.cpp
+++ b/src/mongo/client/sdam/topology_state_machine_test.cpp
@@ -88,7 +88,7 @@ protected:
// update the known hosts in the ServerDescription
if (testCase.initialConfig.getSeedList()) {
- for (auto address : *testCase.initialConfig.getSeedList()) {
+ for (const auto& address : *testCase.initialConfig.getSeedList()) {
serverDescriptionBuilder.withHost(address);
}
}
@@ -461,7 +461,7 @@ TEST_F(TopologyStateMachineTestFixture, ShouldNotUpdateToplogyType) {
}
int count = 0;
- for (auto testCase : testCases) {
+ for (const auto& testCase : testCases) {
std::cout << "case " << ++count << " starting TopologyType: " << toString(testCase.starting)
<< "; incoming ServerType: " << toString(testCase.incoming)
<< "; expect ending TopologyType: " << toString(testCase.ending) << std::endl;
@@ -530,7 +530,7 @@ TEST_F(TopologyStateMachineTestFixture, ShouldUpdateToCorrectToplogyType) {
TopologyType::kReplicaSetNoPrimary}};
int count = 0;
- for (auto testCase : testCases) {
+ for (const auto& testCase : testCases) {
std::cout << "case " << ++count << " starting TopologyType: " << toString(testCase.starting)
<< "; incoming ServerType: " << toString(testCase.incoming)
<< "; expect ending TopologyType: " << toString(testCase.ending) << std::endl;
diff --git a/src/mongo/client/server_discovery_monitor.cpp b/src/mongo/client/server_discovery_monitor.cpp
index cc4821d0cac..a7c88b6372c 100644
--- a/src/mongo/client/server_discovery_monitor.cpp
+++ b/src/mongo/client/server_discovery_monitor.cpp
@@ -478,7 +478,7 @@ void ServerDiscoveryMonitor::shutdown() {
return;
_isShutdown = true;
- for (auto singleMonitor : _singleMonitors) {
+ for (const auto& singleMonitor : _singleMonitors) {
singleMonitor.second->shutdown();
}
}
diff --git a/src/mongo/client/streamable_replica_set_monitor.cpp b/src/mongo/client/streamable_replica_set_monitor.cpp
index 182df9c7438..960eea40256 100644
--- a/src/mongo/client/streamable_replica_set_monitor.cpp
+++ b/src/mongo/client/streamable_replica_set_monitor.cpp
@@ -107,7 +107,7 @@ std::string readPrefToStringFull(const ReadPreferenceSetting& readPref) {
std::string hostListToString(boost::optional<std::vector<HostAndPort>> x) {
std::stringstream s;
if (x) {
- for (auto h : *x) {
+ for (const auto& h : *x) {
s << h.toString() << "; ";
}
}
@@ -607,7 +607,7 @@ void StreamableReplicaSetMonitor::appendInfo(BSONObjBuilder& bsonObjBuilder, boo
BSONObjBuilder monitorInfo(bsonObjBuilder.subobjStart(getName()));
if (forFTDC) {
- for (auto serverDescription : topologyDescription->getServers()) {
+ for (const auto& serverDescription : topologyDescription->getServers()) {
monitorInfo.appendNumber(serverDescription->getAddress().toString(),
pingTimeMillis(serverDescription));
}
diff --git a/src/mongo/crypto/fle_crypto.cpp b/src/mongo/crypto/fle_crypto.cpp
index de05c0f517a..1f1ba117b5f 100644
--- a/src/mongo/crypto/fle_crypto.cpp
+++ b/src/mongo/crypto/fle_crypto.cpp
@@ -2714,7 +2714,7 @@ void EDCServerCollection::validateEncryptedFieldInfo(BSONObj& obj,
const EncryptedFieldConfig& efc,
bool bypassDocumentValidation) {
stdx::unordered_set<std::string> indexedFields;
- for (auto f : efc.getFields()) {
+ for (const auto& f : efc.getFields()) {
if (f.getQueries().has_value()) {
indexedFields.insert(f.getPath().toString());
}
diff --git a/src/mongo/db/active_index_builds.cpp b/src/mongo/db/active_index_builds.cpp
index e9041058530..b0452c0823e 100644
--- a/src/mongo/db/active_index_builds.cpp
+++ b/src/mongo/db/active_index_builds.cpp
@@ -161,7 +161,7 @@ std::vector<std::shared_ptr<ReplIndexBuildState>> ActiveIndexBuilds::_filterInde
WithLock lk, IndexBuildFilterFn indexBuildFilter) const {
std::vector<std::shared_ptr<ReplIndexBuildState>> indexBuilds;
- for (auto pair : _allIndexBuilds) {
+ for (const auto& pair : _allIndexBuilds) {
auto replState = pair.second;
if (!indexBuildFilter(*replState)) {
continue;
@@ -192,7 +192,7 @@ Status ActiveIndexBuilds::registerIndexBuild(
return replIndexBuildState->collectionUUID == replState.collectionUUID;
};
auto collIndexBuilds = _filterIndexBuilds_inlock(lk, pred);
- for (auto existingIndexBuild : collIndexBuilds) {
+ for (const auto& existingIndexBuild : collIndexBuilds) {
for (const auto& name : replIndexBuildState->indexNames) {
if (existingIndexBuild->indexNames.end() !=
std::find(existingIndexBuild->indexNames.begin(),
diff --git a/src/mongo/db/catalog/catalog_control.cpp b/src/mongo/db/catalog/catalog_control.cpp
index 79b3126d9ff..7f4dc6167e8 100644
--- a/src/mongo/db/catalog/catalog_control.cpp
+++ b/src/mongo/db/catalog/catalog_control.cpp
@@ -256,7 +256,7 @@ void openCatalog(OperationContext* opCtx,
// indexes on that collection are done at once, so we use a map to group them together.
stdx::unordered_map<NamespaceString, IndexNameObjs> nsToIndexNameObjMap;
auto catalog = CollectionCatalog::get(opCtx);
- for (StorageEngine::IndexIdentifier indexIdentifier : reconcileResult.indexesToRebuild) {
+ for (const StorageEngine::IndexIdentifier& indexIdentifier : reconcileResult.indexesToRebuild) {
auto indexName = indexIdentifier.indexName;
auto coll = catalog->lookupCollectionByNamespace(opCtx, indexIdentifier.nss);
auto indexSpecs = getIndexNameObjs(
diff --git a/src/mongo/db/catalog/index_builds_manager_test.cpp b/src/mongo/db/catalog/index_builds_manager_test.cpp
index 8e986dad1b5..1c5e62cd865 100644
--- a/src/mongo/db/catalog/index_builds_manager_test.cpp
+++ b/src/mongo/db/catalog/index_builds_manager_test.cpp
@@ -72,7 +72,7 @@ void IndexBuildsManagerTest::createCollection(const NamespaceString& nss) {
std::vector<BSONObj> makeSpecs(const NamespaceString& nss, std::vector<std::string> keys) {
ASSERT(keys.size());
std::vector<BSONObj> indexSpecs;
- for (auto keyName : keys) {
+ for (const auto& keyName : keys) {
indexSpecs.push_back(
BSON("v" << 2 << "key" << BSON(keyName << 1) << "name" << (keyName + "_1")));
}
diff --git a/src/mongo/db/catalog/index_catalog_impl.cpp b/src/mongo/db/catalog/index_catalog_impl.cpp
index 990f0dad60b..b7be978e0e0 100644
--- a/src/mongo/db/catalog/index_catalog_impl.cpp
+++ b/src/mongo/db/catalog/index_catalog_impl.cpp
@@ -1647,7 +1647,7 @@ Status IndexCatalogImpl::_indexRecords(OperationContext* opCtx,
return _indexFilteredRecords(opCtx, coll, index, bsonRecords, keysInsertedOut);
std::vector<BsonRecord> filteredBsonRecords;
- for (auto bsonRecord : bsonRecords) {
+ for (const auto& bsonRecord : bsonRecords) {
if (filter->matchesBSON(*(bsonRecord.docPtr)))
filteredBsonRecords.push_back(bsonRecord);
}
diff --git a/src/mongo/db/catalog/index_consistency.cpp b/src/mongo/db/catalog/index_consistency.cpp
index 94caaf8ee48..596e56b1b0f 100644
--- a/src/mongo/db/catalog/index_consistency.cpp
+++ b/src/mongo/db/catalog/index_consistency.cpp
@@ -157,7 +157,7 @@ void IndexConsistency::repairMissingIndexEntries(OperationContext* opCtx,
if (indexName != index->descriptor()->indexName()) {
// Assuming that _missingIndexEntries is sorted by indexName, this lookup should not
// happen often.
- for (auto currIndex : _validateState->getIndexes()) {
+ for (const auto& currIndex : _validateState->getIndexes()) {
if (currIndex->descriptor()->indexName() == indexName) {
index = currIndex;
break;
diff --git a/src/mongo/db/catalog/views_for_database.cpp b/src/mongo/db/catalog/views_for_database.cpp
index 2ebf6c18b91..b588c69f862 100644
--- a/src/mongo/db/catalog/views_for_database.cpp
+++ b/src/mongo/db/catalog/views_for_database.cpp
@@ -200,7 +200,7 @@ Status ViewsForDatabase::upsertIntoGraph(OperationContext* opCtx,
refs.push_back(viewDef.viewOn());
int pipelineSize = 0;
- for (auto obj : viewDef.pipeline()) {
+ for (const auto& obj : viewDef.pipeline()) {
pipelineSize += obj.objsize();
}
diff --git a/src/mongo/db/commands/command_mirroring_test.cpp b/src/mongo/db/commands/command_mirroring_test.cpp
index 99db08a6df5..6afb28d8718 100644
--- a/src/mongo/db/commands/command_mirroring_test.cpp
+++ b/src/mongo/db/commands/command_mirroring_test.cpp
@@ -61,7 +61,7 @@ public:
bob << commandName() << coll;
bob << "lsid" << _lsid.toBSON();
- for (auto arg : args) {
+ for (const auto& arg : args) {
bob << arg.firstElement();
}
@@ -233,7 +233,7 @@ public:
void checkFieldNamesAreAllowed(BSONObj& mirroredObj) {
const auto possibleKeys = getAllowedKeys();
- for (auto key : mirroredObj.getFieldNames<std::set<std::string>>()) {
+ for (const auto& key : mirroredObj.getFieldNames<std::set<std::string>>()) {
ASSERT(std::find(possibleKeys.begin(), possibleKeys.end(), key) != possibleKeys.end());
}
}
diff --git a/src/mongo/db/commands/dbhash.cpp b/src/mongo/db/commands/dbhash.cpp
index 4b63110308c..627e2fe4d86 100644
--- a/src/mongo/db/commands/dbhash.cpp
+++ b/src/mongo/db/commands/dbhash.cpp
@@ -278,17 +278,17 @@ public:
BSONArrayBuilder cappedCollections;
BSONObjBuilder collectionsByUUID;
- for (auto elem : cappedCollectionSet) {
+ for (const auto& elem : cappedCollectionSet) {
cappedCollections.append(elem);
}
- for (auto entry : collectionToUUIDMap) {
+ for (const auto& entry : collectionToUUIDMap) {
auto collName = entry.first;
auto uuid = entry.second;
uuid.appendToBuilder(&collectionsByUUID, collName);
}
- for (auto entry : collectionToHashMap) {
+ for (const auto& entry : collectionToHashMap) {
auto collName = entry.first;
auto hash = entry.second;
bb.append(collName, hash);
diff --git a/src/mongo/db/curop.cpp b/src/mongo/db/curop.cpp
index db67644cd1b..9c362854d97 100644
--- a/src/mongo/db/curop.cpp
+++ b/src/mongo/db/curop.cpp
@@ -1427,7 +1427,7 @@ std::function<BSONObj(ProfileFilter::Args)> OpDebug::appendStaged(StringSet requ
return [pieces = std::move(pieces)](ProfileFilter::Args args) {
BSONObjBuilder bob;
- for (auto piece : pieces) {
+ for (const auto& piece : pieces) {
piece(args, bob);
}
return bob.obj();
diff --git a/src/mongo/db/exec/sbe/sbe_hash_join_test.cpp b/src/mongo/db/exec/sbe/sbe_hash_join_test.cpp
index 4bdcedb31a0..79b19a8ed7c 100644
--- a/src/mongo/db/exec/sbe/sbe_hash_join_test.cpp
+++ b/src/mongo/db/exec/sbe/sbe_hash_join_test.cpp
@@ -117,7 +117,7 @@ TEST_F(HashJoinStageTest, HashJoinCollationTest) {
// make sure all the expected pairs occur in the result
ASSERT_EQ(resultsView->size(), expectedVec.size());
- for (auto [outer, inner] : expectedVec) {
+ for (const auto& [outer, inner] : expectedVec) {
auto [expectedTag, expectedVal] = stage_builder::makeValue(BSON_ARRAY(outer << inner));
bool found = false;
for (size_t i = 0; i < resultsView->size(); i++) {
diff --git a/src/mongo/db/exec/sbe/stages/column_scan.cpp b/src/mongo/db/exec/sbe/stages/column_scan.cpp
index bf83c0aca29..edc2f2e66cd 100644
--- a/src/mongo/db/exec/sbe/stages/column_scan.cpp
+++ b/src/mongo/db/exec/sbe/stages/column_scan.cpp
@@ -712,7 +712,7 @@ std::unique_ptr<PlanStageStats> ColumnScanStage::getStats(bool includeDebugInfo)
bob.appendNumber("numRowStoreFetches",
static_cast<long long>(_specificStats.numRowStoreFetches));
BSONObjBuilder columns(bob.subobjStart("columns"));
- for (ColumnScanStats::CursorStats cursorStat : _specificStats.cursorStats) {
+ for (const ColumnScanStats::CursorStats& cursorStat : _specificStats.cursorStats) {
StringData path = cursorStat.path;
if (path == ColumnStore::kRowIdPath) {
path = "<<RowId Column>>";
@@ -726,7 +726,7 @@ std::unique_ptr<PlanStageStats> ColumnScanStage::getStats(bool includeDebugInfo)
columns.done();
BSONObjBuilder parentColumns(bob.subobjStart("parentColumns"));
- for (ColumnScanStats::CursorStats cursorStat : _specificStats.parentCursorStats) {
+ for (const ColumnScanStats::CursorStats& cursorStat : _specificStats.parentCursorStats) {
StringData path = cursorStat.path;
BSONObjBuilder column(parentColumns.subobjStart(path));
column.appendNumber("numNexts", static_cast<long long>(cursorStat.numNexts));
diff --git a/src/mongo/db/exec/sbe/util/stage_results_printer.cpp b/src/mongo/db/exec/sbe/util/stage_results_printer.cpp
index 94d2f6f3886..2a8c740cad8 100644
--- a/src/mongo/db/exec/sbe/util/stage_results_printer.cpp
+++ b/src/mongo/db/exec/sbe/util/stage_results_printer.cpp
@@ -58,7 +58,7 @@ void StageResultsPrinter<T>::printStageResults(CompileCtx* ctx,
const SlotNames& slotNames,
PlanStage* stage) {
std::vector<value::SlotAccessor*> accessors;
- for (auto slot : slotNames) {
+ for (const auto& slot : slotNames) {
accessors.push_back(stage->getAccessor(*ctx, slot.first));
}
@@ -92,7 +92,7 @@ template <typename T>
void StageResultsPrinter<T>::printSlotNames(const SlotNames& slotNames) {
_stream << "[";
bool first = true;
- for (auto slot : slotNames) {
+ for (const auto& slot : slotNames) {
if (!first) {
_stream << ", ";
} else {
diff --git a/src/mongo/db/exec/sbe/values/column_store_encoder_test.cpp b/src/mongo/db/exec/sbe/values/column_store_encoder_test.cpp
index f47faa329c7..35bfb95ba5c 100644
--- a/src/mongo/db/exec/sbe/values/column_store_encoder_test.cpp
+++ b/src/mongo/db/exec/sbe/values/column_store_encoder_test.cpp
@@ -368,7 +368,7 @@ TEST(SBEColumnStoreEncoder, ColumnsWithEmbeddedBSONElements) {
value::ColumnStoreEncoder encoder;
auto cellCursor = cellView.subcellValuesGenerator(&encoder);
- for (auto comparison : testComparisons) {
+ for (const auto& comparison : testComparisons) {
auto cellValue = cellCursor.nextValue();
ASSERT(cellValue);
diff --git a/src/mongo/db/geo/r2_region_coverer_test.cpp b/src/mongo/db/geo/r2_region_coverer_test.cpp
index 4287a3fbc5e..eff96a0c5f7 100644
--- a/src/mongo/db/geo/r2_region_coverer_test.cpp
+++ b/src/mongo/db/geo/r2_region_coverer_test.cpp
@@ -786,7 +786,7 @@ TEST(R2CellUnion, Contains) {
generateRandomCells(GeoHash(), false, &unnormalized, &normalized);
R2CellUnion cellUnion;
cellUnion.init(normalized);
- for (auto cellId : normalized) {
+ for (const auto& cellId : normalized) {
testContains(cellUnion, cellId, 100);
}
}
@@ -794,7 +794,7 @@ TEST(R2CellUnion, Contains) {
// Naive implementation of intersects to test correctness
bool intersects(const R2CellUnion& cellUnion, GeoHash cellId) {
- for (auto unionCellId : cellUnion.cellIds()) {
+ for (const auto& unionCellId : cellUnion.cellIds()) {
// Two cells will only intersect if one contains the other
if (unionCellId.contains(cellId) || cellId.contains(unionCellId)) {
return true;
@@ -828,7 +828,7 @@ TEST(R2CellUnion, Intersects) {
// An R2CellUnion should intersect with every cell that contains a member of the union.
// It should also intersect with cells it contains
- for (auto cellId : randomUnion.cellIds()) {
+ for (const auto& cellId : randomUnion.cellIds()) {
for (unsigned level = 0; level <= 32; ++level) {
ASSERT_TRUE(randomUnion.intersects(GeoHash(cellId.getHash(), level)));
}
@@ -888,14 +888,14 @@ void testDifference(std::vector<GeoHash>& xCellIds, std::vector<GeoHash>& yCellI
xUnionY.init(x.cellIds());
xUnionY.add(y.cellIds());
- for (auto cellId : xUnionY.cellIds()) {
+ for (const auto& cellId : xUnionY.cellIds()) {
ASSERT_TRUE(xMinusYPlusY.contains(cellId));
ASSERT_TRUE(yMinusXPlusX.contains(cellId));
}
- for (auto cellId : xMinusYPlusY.cellIds()) {
+ for (const auto& cellId : xMinusYPlusY.cellIds()) {
ASSERT_TRUE(xUnionY.contains(cellId));
}
- for (auto cellId : yMinusXPlusX.cellIds()) {
+ for (const auto& cellId : yMinusXPlusX.cellIds()) {
ASSERT_TRUE(xUnionY.contains(cellId));
}
}
diff --git a/src/mongo/db/index/column_key_generator_test.cpp b/src/mongo/db/index/column_key_generator_test.cpp
index 5e75e4ea674..f235af478b8 100644
--- a/src/mongo/db/index/column_key_generator_test.cpp
+++ b/src/mongo/db/index/column_key_generator_test.cpp
@@ -337,7 +337,7 @@ std::unique_ptr<ColumnKeyGenerator> makeKeyGen(BSONObj columnstoreProjection = B
ProjPairVector expectedProjPairs(std::vector<std::pair<BSONObj, StringSet>> bsonPairs) {
ProjPairVector projPairs;
- for (auto [projection, fields] : bsonPairs) {
+ for (const auto& [projection, fields] : bsonPairs) {
projPairs.push_back({makeKeyGen(projection), fields});
}
return projPairs;
diff --git a/src/mongo/db/index/index_access_method.cpp b/src/mongo/db/index/index_access_method.cpp
index a07acae57e0..ec2c609a86e 100644
--- a/src/mongo/db/index/index_access_method.cpp
+++ b/src/mongo/db/index/index_access_method.cpp
@@ -178,7 +178,7 @@ Status SortedDataIndexAccessMethod::insert(OperationContext* opCtx,
const std::vector<BsonRecord>& bsonRecords,
const InsertDeleteOptions& options,
int64_t* numInserted) {
- for (auto bsonRecord : bsonRecords) {
+ for (const auto& bsonRecord : bsonRecords) {
invariant(bsonRecord.id != RecordId());
if (!bsonRecord.ts.isNull()) {
diff --git a/src/mongo/db/index_builds_coordinator.cpp b/src/mongo/db/index_builds_coordinator.cpp
index 0342d563301..e9954ef1e3a 100644
--- a/src/mongo/db/index_builds_coordinator.cpp
+++ b/src/mongo/db/index_builds_coordinator.cpp
@@ -674,7 +674,7 @@ Status IndexBuildsCoordinator::_setUpResumeIndexBuild(OperationContext* opCtx,
invariant(collection);
auto durableCatalog = DurableCatalog::get(opCtx);
- for (auto spec : specs) {
+ for (const auto& spec : specs) {
std::string indexName =
spec.getStringField(IndexDescriptor::kIndexNameFieldName).toString();
if (indexName.empty()) {
@@ -761,7 +761,7 @@ std::vector<UUID> IndexBuildsCoordinator::abortCollectionIndexBuilds(
"reason"_attr = reason);
std::vector<UUID> buildUUIDs;
- for (auto replState : collIndexBuilds) {
+ for (const auto& replState : collIndexBuilds) {
if (abortIndexBuildByBuildUUID(
opCtx, replState->buildUUID, IndexBuildAction::kPrimaryAbort, reason)) {
buildUUIDs.push_back(replState->buildUUID);
@@ -782,7 +782,7 @@ void IndexBuildsCoordinator::abortDatabaseIndexBuilds(OperationContext* opCtx,
auto indexBuildFilter = [=](const auto& replState) { return dbName == replState.dbName; };
return activeIndexBuilds.filterIndexBuilds(indexBuildFilter);
}();
- for (auto replState : builds) {
+ for (const auto& replState : builds) {
if (!abortIndexBuildByBuildUUID(
opCtx, replState->buildUUID, IndexBuildAction::kPrimaryAbort, reason)) {
// The index build may already be in the midst of tearing down.
@@ -818,7 +818,7 @@ void IndexBuildsCoordinator::abortTenantIndexBuilds(OperationContext* opCtx,
buildsWaitingToFinish.reserve(builds.size());
const auto indexBuildActionStr =
indexBuildActionToString(IndexBuildAction::kTenantMigrationAbort);
- for (auto replState : builds) {
+ for (const auto& replState : builds) {
if (!abortIndexBuildByBuildUUID(
opCtx, replState->buildUUID, IndexBuildAction::kTenantMigrationAbort, reason)) {
// The index build may already be in the midst of tearing down.
@@ -853,7 +853,7 @@ void IndexBuildsCoordinator::abortAllIndexBuildsForInitialSync(OperationContext*
auto indexBuildFilter = [](const auto& replState) { return true; };
return activeIndexBuilds.filterIndexBuilds(indexBuildFilter);
}();
- for (auto replState : builds) {
+ for (const auto& replState : builds) {
if (!abortIndexBuildByBuildUUID(
opCtx, replState->buildUUID, IndexBuildAction::kInitialSyncAbort, reason)) {
// The index build may already be in the midst of tearing down.
@@ -1056,7 +1056,7 @@ void IndexBuildsCoordinator::applyCommitIndexBuild(OperationContext* opCtx,
// Restart the 'paused' index build in the background.
IndexBuilds buildsToRestart;
IndexBuildDetails details{collUUID};
- for (auto spec : oplogEntry.indexSpecs) {
+ for (const auto& spec : oplogEntry.indexSpecs) {
details.indexSpecs.emplace_back(spec.getOwned());
}
buildsToRestart.insert({buildUUID, details});
@@ -1528,7 +1528,7 @@ IndexBuilds IndexBuildsCoordinator::stopIndexBuildsForRollback(OperationContext*
// Record the index builds aborted due to rollback. This allows any rollback algorithm
// to efficiently restart all unfinished index builds without having to scan all indexes
// in all collections.
- for (auto spec : replState->indexSpecs) {
+ for (const auto& spec : replState->indexSpecs) {
aborted.indexSpecs.emplace_back(spec.getOwned());
}
buildsStopped.insert({replState->buildUUID, aborted});
diff --git a/src/mongo/db/index_builds_coordinator_mongod_test.cpp b/src/mongo/db/index_builds_coordinator_mongod_test.cpp
index 14a0ade7dec..571ff3d6c33 100644
--- a/src/mongo/db/index_builds_coordinator_mongod_test.cpp
+++ b/src/mongo/db/index_builds_coordinator_mongod_test.cpp
@@ -112,7 +112,7 @@ void IndexBuildsCoordinatorMongodTest::createCollection(const NamespaceString& n
std::vector<BSONObj> makeSpecs(const NamespaceString& nss, std::vector<std::string> keys) {
invariant(keys.size());
std::vector<BSONObj> indexSpecs;
- for (auto keyName : keys) {
+ for (const auto& keyName : keys) {
indexSpecs.push_back(
BSON("v" << 2 << "key" << BSON(keyName << 1) << "name" << (keyName + "_1")));
}
diff --git a/src/mongo/db/matcher/expression_algo.cpp b/src/mongo/db/matcher/expression_algo.cpp
index c677f6b92e6..65959a487e8 100644
--- a/src/mongo/db/matcher/expression_algo.cpp
+++ b/src/mongo/db/matcher/expression_algo.cpp
@@ -782,7 +782,7 @@ bool containsDependency(const OrderedPathSet& testSet, const OrderedPathSet& pre
PathComparator pathComparator;
auto i2 = testSet.begin();
- for (auto p1 : prefixCandidates) {
+ for (const auto& p1 : prefixCandidates) {
while (pathComparator(*i2, p1)) {
++i2;
if (i2 == testSet.end()) {
diff --git a/src/mongo/db/matcher/expression_algo_test.cpp b/src/mongo/db/matcher/expression_algo_test.cpp
index 96117ff162a..15b2ab0e927 100644
--- a/src/mongo/db/matcher/expression_algo_test.cpp
+++ b/src/mongo/db/matcher/expression_algo_test.cpp
@@ -928,7 +928,7 @@ TEST(IsIndependent, NonRenameableExpressionIsNotIndependent) {
" {a: {$_internalSchemaObjectMatch: {b: 2}}}]}",
"{$or: [{a: {$elemMatch: {b: 3}}}, {a: {$elemMatch: {b: 4}}}]}"};
- for (auto str : stringExpressions) {
+ for (const auto& str : stringExpressions) {
BSONObj matchPredicate = fromjson(str);
boost::intrusive_ptr<ExpressionContextForTest> expCtx(new ExpressionContextForTest());
auto swMatchExpression = MatchExpressionParser::parse(matchPredicate, std::move(expCtx));
diff --git a/src/mongo/db/matcher/expression_path.h b/src/mongo/db/matcher/expression_path.h
index 2e30772fb8d..63d761f963c 100644
--- a/src/mongo/db/matcher/expression_path.h
+++ b/src/mongo/db/matcher/expression_path.h
@@ -91,7 +91,7 @@ public:
void applyRename(const StringMap<std::string>& renameList) {
size_t renamesFound = 0u;
std::string rewrittenPath;
- for (auto rename : renameList) {
+ for (const auto& rename : renameList) {
if (rename.first == path()) {
rewrittenPath = rename.second;
diff --git a/src/mongo/db/matcher/rewrite_expr.cpp b/src/mongo/db/matcher/rewrite_expr.cpp
index 3ca73b289b0..148fe0025bd 100644
--- a/src/mongo/db/matcher/rewrite_expr.cpp
+++ b/src/mongo/db/matcher/rewrite_expr.cpp
@@ -233,7 +233,7 @@ bool RewriteExpr::_canRewriteComparison(
const auto& operandList = expression->getOperandList();
bool hasFieldPath = false;
- for (auto& operand : operandList) {
+ for (const auto& operand : operandList) {
if (auto exprFieldPath = dynamic_cast<ExpressionFieldPath*>(operand.get())) {
if (exprFieldPath->isVariableReference() || exprFieldPath->isROOT()) {
// Rather than a local document field path, this field path refers to either a
diff --git a/src/mongo/db/mirror_maestro.cpp b/src/mongo/db/mirror_maestro.cpp
index 5be4cf1e0bc..172b7ce6bda 100644
--- a/src/mongo/db/mirror_maestro.cpp
+++ b/src/mongo/db/mirror_maestro.cpp
@@ -218,7 +218,7 @@ public:
BSONObj toBSON() const noexcept {
stdx::lock_guard<Mutex> lk(_mutex);
BSONObjBuilder bob;
- for (auto entry : _resolved) {
+ for (const auto& entry : _resolved) {
bob.append(entry.first, entry.second);
}
return bob.obj();
diff --git a/src/mongo/db/mirroring_sampler_test.cpp b/src/mongo/db/mirroring_sampler_test.cpp
index 7fcec049007..76ef352b7d2 100644
--- a/src/mongo/db/mirroring_sampler_test.cpp
+++ b/src/mongo/db/mirroring_sampler_test.cpp
@@ -101,13 +101,13 @@ public:
}
void resetHitCounts() {
- for (auto pair : _hitCounts) {
+ for (const auto& pair : _hitCounts) {
_hitCounts[pair.first] = 0;
}
}
void populteHitCounts(std::vector<HostAndPort>& targets) {
- for (auto host : targets) {
+ for (const auto& host : targets) {
auto it = _hitCounts.find(host.toString());
invariant(it != _hitCounts.end());
it->second++;
@@ -129,7 +129,7 @@ public:
double getHitCountsSTD() {
const auto mean = getHitCounsMean();
double standardDeviation = 0.0;
- for (auto pair : _hitCounts) {
+ for (const auto& pair : _hitCounts) {
standardDeviation += std::pow(pair.second - mean, 2);
}
diff --git a/src/mongo/db/op_observer/op_observer_impl.cpp b/src/mongo/db/op_observer/op_observer_impl.cpp
index f1a7d35d439..fd00a18e7fd 100644
--- a/src/mongo/db/op_observer/op_observer_impl.cpp
+++ b/src/mongo/db/op_observer/op_observer_impl.cpp
@@ -399,7 +399,7 @@ void OpObserverImpl::onStartIndexBuild(OperationContext* opCtx,
indexBuildUUID.appendToBuilder(&oplogEntryBuilder, "indexBuildUUID");
BSONArrayBuilder indexesArr(oplogEntryBuilder.subarrayStart("indexes"));
- for (auto indexDoc : indexes) {
+ for (const auto& indexDoc : indexes) {
indexesArr.append(indexDoc);
}
indexesArr.done();
@@ -464,7 +464,7 @@ void OpObserverImpl::onCommitIndexBuild(OperationContext* opCtx,
indexBuildUUID.appendToBuilder(&oplogEntryBuilder, "indexBuildUUID");
BSONArrayBuilder indexesArr(oplogEntryBuilder.subarrayStart("indexes"));
- for (auto indexDoc : indexes) {
+ for (const auto& indexDoc : indexes) {
indexesArr.append(indexDoc);
}
indexesArr.done();
@@ -493,7 +493,7 @@ void OpObserverImpl::onAbortIndexBuild(OperationContext* opCtx,
indexBuildUUID.appendToBuilder(&oplogEntryBuilder, "indexBuildUUID");
BSONArrayBuilder indexesArr(oplogEntryBuilder.subarrayStart("indexes"));
- for (auto indexDoc : indexes) {
+ for (const auto& indexDoc : indexes) {
indexesArr.append(indexDoc);
}
indexesArr.done();
diff --git a/src/mongo/db/ops/parsed_update_array_filters.cpp b/src/mongo/db/ops/parsed_update_array_filters.cpp
index 342a1323267..9282fb8c64e 100644
--- a/src/mongo/db/ops/parsed_update_array_filters.cpp
+++ b/src/mongo/db/ops/parsed_update_array_filters.cpp
@@ -37,7 +37,7 @@ parsedUpdateArrayFilters(const boost::intrusive_ptr<ExpressionContext>& expCtx,
const std::vector<BSONObj>& rawArrayFiltersIn,
const NamespaceString& nss) {
std::map<StringData, std::unique_ptr<ExpressionWithPlaceholder>> arrayFiltersOut;
- for (auto rawArrayFilter : rawArrayFiltersIn) {
+ for (const auto& rawArrayFilter : rawArrayFiltersIn) {
auto parsedArrayFilter =
MatchExpressionParser::parse(rawArrayFilter,
expCtx,
diff --git a/src/mongo/db/pipeline/document_source_densify.cpp b/src/mongo/db/pipeline/document_source_densify.cpp
index addddc34708..427ce8d9da0 100644
--- a/src/mongo/db/pipeline/document_source_densify.cpp
+++ b/src/mongo/db/pipeline/document_source_densify.cpp
@@ -183,7 +183,7 @@ SortPattern getSortPatternForDensify(RangeStatement rangeStatement,
std::vector<SortPatternPart> sortParts;
// We do not add partitions to the sort spec if the range is "full".
if (!stdx::holds_alternative<Full>(rangeStatement.getBounds())) {
- for (auto partition : partitions) {
+ for (const auto& partition : partitions) {
SortPatternPart part;
part.fieldPath = partition.fullPath();
sortParts.push_back(std::move(part));
diff --git a/src/mongo/db/pipeline/document_source_graph_lookup.cpp b/src/mongo/db/pipeline/document_source_graph_lookup.cpp
index 666d8952284..78761b412bd 100644
--- a/src/mongo/db/pipeline/document_source_graph_lookup.cpp
+++ b/src/mongo/db/pipeline/document_source_graph_lookup.cpp
@@ -478,7 +478,7 @@ void DocumentSourceGraphLookUp::performSearch() {
// If _startWith evaluates to an array, treat each value as a separate starting point.
if (startingValue.isArray()) {
- for (auto value : startingValue.getArray()) {
+ for (const auto& value : startingValue.getArray()) {
_frontier.insert(value);
_frontierUsageBytes += value.getApproximateSize();
}
diff --git a/src/mongo/db/pipeline/document_source_group.cpp b/src/mongo/db/pipeline/document_source_group.cpp
index d0fe18d0078..c7ccdaa4d73 100644
--- a/src/mongo/db/pipeline/document_source_group.cpp
+++ b/src/mongo/db/pipeline/document_source_group.cpp
@@ -746,7 +746,7 @@ shared_ptr<Sorter<Value, Value>::Iterator> DocumentSourceGroup::spill() {
_groups->clear();
// Zero out the current per-accumulation statement memory consumption, as the memory has been
// freed by spilling.
- for (auto accum : _accumulatedFields) {
+ for (const auto& accum : _accumulatedFields) {
_memoryTracker.set(accum.fieldName, 0);
}
diff --git a/src/mongo/db/pipeline/document_source_internal_unpack_bucket_test/optimize_lastpoint_test.cpp b/src/mongo/db/pipeline/document_source_internal_unpack_bucket_test/optimize_lastpoint_test.cpp
index a170819aa3c..77cfaadabde 100644
--- a/src/mongo/db/pipeline/document_source_internal_unpack_bucket_test/optimize_lastpoint_test.cpp
+++ b/src/mongo/db/pipeline/document_source_internal_unpack_bucket_test/optimize_lastpoint_test.cpp
@@ -44,7 +44,7 @@ void assertExpectedLastpointOpt(const boost::intrusive_ptr<ExpressionContext> ex
const std::vector<std::string>& expectedPipelineStrs,
const bool expectedSuccess = true) {
std::vector<BSONObj> inputPipelineBson;
- for (auto stageStr : inputPipelineStrs) {
+ for (const auto& stageStr : inputPipelineStrs) {
inputPipelineBson.emplace_back(fromjson(stageStr));
}
@@ -62,7 +62,7 @@ void assertExpectedLastpointOpt(const boost::intrusive_ptr<ExpressionContext> ex
// Assert the pipeline is unchanged.
auto serializedItr = serialized.begin();
- for (auto stageStr : expectedPipelineStrs) {
+ for (const auto& stageStr : expectedPipelineStrs) {
auto expectedStageBson = fromjson(stageStr);
ASSERT_BSONOBJ_EQ(*serializedItr, expectedStageBson);
++serializedItr;
diff --git a/src/mongo/db/pipeline/document_source_lookup.cpp b/src/mongo/db/pipeline/document_source_lookup.cpp
index 11fe6ebdf4a..20253fec682 100644
--- a/src/mongo/db/pipeline/document_source_lookup.cpp
+++ b/src/mongo/db/pipeline/document_source_lookup.cpp
@@ -1025,7 +1025,7 @@ void DocumentSourceLookUp::serializeToArray(
}
if (!hasLocalFieldForeignFieldJoin() || pipeline.size() > 0) {
MutableDocument exprList;
- for (auto letVar : _letVariables) {
+ for (const auto& letVar : _letVariables) {
exprList.addField(letVar.name,
letVar.expression->serialize(static_cast<bool>(explain)));
}
diff --git a/src/mongo/db/pipeline/document_source_merge.cpp b/src/mongo/db/pipeline/document_source_merge.cpp
index d9f6d06179b..d48bbe5491f 100644
--- a/src/mongo/db/pipeline/document_source_merge.cpp
+++ b/src/mongo/db/pipeline/document_source_merge.cpp
@@ -552,7 +552,7 @@ Value DocumentSourceMerge::serialize(boost::optional<ExplainOptions::Verbosity>
spec.setWhenNotMatched(_descriptor.mode.second);
spec.setOn([&]() {
std::vector<std::string> mergeOnFields;
- for (auto path : _mergeOnFields) {
+ for (const auto& path : _mergeOnFields) {
mergeOnFields.push_back(path.fullPath());
}
return mergeOnFields;
diff --git a/src/mongo/db/pipeline/document_source_queue.cpp b/src/mongo/db/pipeline/document_source_queue.cpp
index c724db5ae10..77efefd5249 100644
--- a/src/mongo/db/pipeline/document_source_queue.cpp
+++ b/src/mongo/db/pipeline/document_source_queue.cpp
@@ -82,7 +82,7 @@ DocumentSource::GetNextResult DocumentSourceQueue::doGetNext() {
Value DocumentSourceQueue::serialize(boost::optional<ExplainOptions::Verbosity> explain) const {
ValueArrayStream vals;
- for (auto elem : _queue) {
+ for (const auto& elem : _queue) {
vals << elem.getDocument().getOwned();
}
return Value(DOC(kStageName << vals.done()));
diff --git a/src/mongo/db/pipeline/document_source_set_window_fields.cpp b/src/mongo/db/pipeline/document_source_set_window_fields.cpp
index f21394ae338..0200ce21cc7 100644
--- a/src/mongo/db/pipeline/document_source_set_window_fields.cpp
+++ b/src/mongo/db/pipeline/document_source_set_window_fields.cpp
@@ -239,7 +239,7 @@ list<intrusive_ptr<DocumentSource>> document_source_set_window_fields::create(
combined.emplace_back(std::move(part));
}
if (sortBy) {
- for (auto part : *sortBy) {
+ for (const auto& part : *sortBy) {
combined.push_back(part);
}
}
diff --git a/src/mongo/db/pipeline/expression.h b/src/mongo/db/pipeline/expression.h
index 918173b50ba..83ac940f999 100644
--- a/src/mongo/db/pipeline/expression.h
+++ b/src/mongo/db/pipeline/expression.h
@@ -559,7 +559,7 @@ public:
// Verify that '_output' produces an array and pass each element to 'process'.
auto output = _output->evaluate(root, variables);
uassert(5788200, "Input must be an array", output.isArray());
- for (auto& item : output.getArray()) {
+ for (const auto& item : output.getArray()) {
accum.process(item, false);
}
return accum.getValue(false);
diff --git a/src/mongo/db/pipeline/expression_bm.cpp b/src/mongo/db/pipeline/expression_bm.cpp
index 6978d426c42..0d2a2e798c3 100644
--- a/src/mongo/db/pipeline/expression_bm.cpp
+++ b/src/mongo/db/pipeline/expression_bm.cpp
@@ -57,7 +57,7 @@ void benchmarkExpression(BSONObj expressionSpec,
// Run the test.
for (auto keepRunning : state) {
- for (auto document : documents) {
+ for (const auto& document : documents) {
benchmark::DoNotOptimize(expression->evaluate(document, variables));
}
benchmark::ClobberMemory();
diff --git a/src/mongo/db/pipeline/expression_convert_test.cpp b/src/mongo/db/pipeline/expression_convert_test.cpp
index 678c29b5b16..4bf42b9b8a5 100644
--- a/src/mongo/db/pipeline/expression_convert_test.cpp
+++ b/src/mongo/db/pipeline/expression_convert_test.cpp
@@ -276,7 +276,7 @@ TEST_F(ExpressionConvertTest, UnsupportedConversionShouldThrowUnlessOnErrorProvi
};
// Attempt all of the unsupported conversions listed above.
- for (auto conversion : unsupportedConversions) {
+ for (const auto& conversion : unsupportedConversions) {
auto inputValue = conversion.first;
auto targetTypeName = conversion.second;
@@ -299,7 +299,7 @@ TEST_F(ExpressionConvertTest, UnsupportedConversionShouldThrowUnlessOnErrorProvi
}
// Attempt them again, this time with an "onError" value.
- for (auto conversion : unsupportedConversions) {
+ for (const auto& conversion : unsupportedConversions) {
auto inputValue = conversion.first;
auto targetTypeName = conversion.second;
diff --git a/src/mongo/db/pipeline/expression_date_test.cpp b/src/mongo/db/pipeline/expression_date_test.cpp
index 97ec344fd9f..1a76e1e1838 100644
--- a/src/mongo/db/pipeline/expression_date_test.cpp
+++ b/src/mongo/db/pipeline/expression_date_test.cpp
@@ -1350,7 +1350,7 @@ TEST_F(ExpressionDateFromStringTest, ReturnsOnErrorForParseFailures) {
std::vector<std::string> invalidDates = {
"60.Monday1770/06:59", "July 4th", "12:50:53", "2017, 12:50:53"};
- for (auto date : invalidDates) {
+ for (const auto& date : invalidDates) {
auto spec = BSON("$dateFromString" << BSON("dateString" << date << "onError"
<< "Error default"));
auto dateExp = Expression::parseExpression(expCtx.get(), spec, expCtx->variablesParseState);
@@ -1363,7 +1363,7 @@ TEST_F(ExpressionDateFromStringTest, ReturnsOnErrorForFormatMismatch) {
const std::string date = "2018/02/06";
std::vector<std::string> unmatchedFormats = {"%Y", "%Y/%m/%d:%H", "Y/m/d"};
- for (auto format : unmatchedFormats) {
+ for (const auto& format : unmatchedFormats) {
auto spec =
BSON("$dateFromString" << BSON("dateString" << date << "format" << format << "onError"
<< "Error default"));
diff --git a/src/mongo/db/pipeline/expression_test.cpp b/src/mongo/db/pipeline/expression_test.cpp
index 2a9978e1bba..fe8a5f19c6a 100644
--- a/src/mongo/db/pipeline/expression_test.cpp
+++ b/src/mongo/db/pipeline/expression_test.cpp
@@ -3916,7 +3916,7 @@ TEST(ExpressionAddTest, VerifyNoDoubleDoubleSummation) {
-9.779323414999364, -546522170658.2997};
double straightSum = 0.0;
DoubleDoubleSummation compensatedSum;
- for (auto x : doubleValues) {
+ for (const auto& x : doubleValues) {
compensatedSum.addDouble(x.getDouble());
straightSum += x.getDouble();
}
diff --git a/src/mongo/db/pipeline/pipeline_test.cpp b/src/mongo/db/pipeline/pipeline_test.cpp
index 62c89ef192f..ed4c9c4cc69 100644
--- a/src/mongo/db/pipeline/pipeline_test.cpp
+++ b/src/mongo/db/pipeline/pipeline_test.cpp
@@ -3292,7 +3292,7 @@ void assertTwoPipelinesOptimizeAndMergeTo(const std::string inputPipe1,
auto pipeline2 = getOptimizedPipeline(input2Bson);
// Merge the pipelines
- for (auto source : pipeline2->getSources()) {
+ for (const auto& source : pipeline2->getSources()) {
pipeline1->pushBack(source);
}
pipeline1->optimizePipeline();
diff --git a/src/mongo/db/pipeline/sharded_agg_helpers.cpp b/src/mongo/db/pipeline/sharded_agg_helpers.cpp
index 68d03d0c96a..e9a7c0c76a8 100644
--- a/src/mongo/db/pipeline/sharded_agg_helpers.cpp
+++ b/src/mongo/db/pipeline/sharded_agg_helpers.cpp
@@ -1305,7 +1305,7 @@ partitionCursors(std::vector<OwnedRemoteCursor> ownedCursors) {
*/
void injectMetaCursor(Pipeline* mergePipeline, std::vector<OwnedRemoteCursor> metaCursors) {
// Provide the "meta" cursors to the $setVariableFromSubPipeline stage.
- for (auto source : mergePipeline->getSources()) {
+ for (const auto& source : mergePipeline->getSources()) {
if (auto* setVarStage =
dynamic_cast<DocumentSourceSetVariableFromSubPipeline*>(source.get())) {
diff --git a/src/mongo/db/pipeline/window_function/window_function_add_to_set_test.cpp b/src/mongo/db/pipeline/window_function/window_function_add_to_set_test.cpp
index d7a2e80dea9..25e444826a6 100644
--- a/src/mongo/db/pipeline/window_function/window_function_add_to_set_test.cpp
+++ b/src/mongo/db/pipeline/window_function/window_function_add_to_set_test.cpp
@@ -42,7 +42,7 @@ public:
WindowFunctionAddToSetTest() : expCtx(getExpCtx()), addToSet(expCtx.get()) {}
void addValuesToWindow(const std::vector<Value>& values) {
- for (auto val : values)
+ for (const auto& val : values)
addToSet.add(val);
}
diff --git a/src/mongo/db/pipeline/window_function/window_function_covariance.cpp b/src/mongo/db/pipeline/window_function/window_function_covariance.cpp
index cab8fdb6193..c9b56a7d1d7 100644
--- a/src/mongo/db/pipeline/window_function/window_function_covariance.cpp
+++ b/src/mongo/db/pipeline/window_function/window_function_covariance.cpp
@@ -47,7 +47,7 @@ bool validateValue(const Value& val) {
Value convertNonFiniteInputValue(Value value) {
int posCnt = 0, negCnt = 0, nanCnt = 0;
bool isDecimal = false;
- for (auto val : value.getArray()) {
+ for (const auto& val : value.getArray()) {
if (val.isNaN()) {
nanCnt++;
} else if (val.getType() == NumberDecimal) {
diff --git a/src/mongo/db/pipeline/window_function/window_function_covariance_test.cpp b/src/mongo/db/pipeline/window_function/window_function_covariance_test.cpp
index 9d1b296a1ef..a170bb97be8 100644
--- a/src/mongo/db/pipeline/window_function/window_function_covariance_test.cpp
+++ b/src/mongo/db/pipeline/window_function/window_function_covariance_test.cpp
@@ -53,7 +53,7 @@ public:
void addToWindowCovariance(WindowFunctionCovariance* covariance,
const std::vector<Value>& valToAdd) {
- for (auto val : valToAdd) {
+ for (const auto& val : valToAdd) {
covariance->add(val);
}
}
diff --git a/src/mongo/db/pipeline/window_function/window_function_integral_test.cpp b/src/mongo/db/pipeline/window_function/window_function_integral_test.cpp
index c929bfa478c..6e6db7086c4 100644
--- a/src/mongo/db/pipeline/window_function/window_function_integral_test.cpp
+++ b/src/mongo/db/pipeline/window_function/window_function_integral_test.cpp
@@ -43,7 +43,7 @@ public:
WindowFunctionIntegralTest() : expCtx(getExpCtx()), integral(expCtx.get()) {}
void addValuesToWindow(const std::vector<Value>& values) {
- for (auto val : values)
+ for (const auto& val : values)
integral.add(val);
}
diff --git a/src/mongo/db/pipeline/window_function/window_function_push_test.cpp b/src/mongo/db/pipeline/window_function/window_function_push_test.cpp
index a7790ee22e6..ac41abe6a67 100644
--- a/src/mongo/db/pipeline/window_function/window_function_push_test.cpp
+++ b/src/mongo/db/pipeline/window_function/window_function_push_test.cpp
@@ -42,7 +42,7 @@ public:
WindowFunctionPushTest() : expCtx(getExpCtx()), push(expCtx.get()) {}
void addValuesToWindow(const std::vector<Value>& values) {
- for (auto val : values)
+ for (const auto& val : values)
push.add(val);
}
diff --git a/src/mongo/db/process_health/state_machine.h b/src/mongo/db/process_health/state_machine.h
index 81d905ae5a5..f9a9e1bd8ed 100644
--- a/src/mongo/db/process_health/state_machine.h
+++ b/src/mongo/db/process_health/state_machine.h
@@ -119,7 +119,7 @@ public:
// Define valid transitions.
// Must be called prior to starting the state machine.
void validTransitions(const TransitionsContainer& transitions) noexcept {
- for (auto [from, toStates] : transitions) {
+ for (const auto& [from, toStates] : transitions) {
for (auto to : toStates) {
validTransition(from, to);
}
diff --git a/src/mongo/db/query/index_bounds_builder_eq_null_test.cpp b/src/mongo/db/query/index_bounds_builder_eq_null_test.cpp
index af4cdf91303..48831ee93a6 100644
--- a/src/mongo/db/query/index_bounds_builder_eq_null_test.cpp
+++ b/src/mongo/db/query/index_bounds_builder_eq_null_test.cpp
@@ -205,7 +205,7 @@ TEST_F(IndexBoundsBuilderTest, TranslateNotEqualToNullShouldBuildExactBoundsIfIn
BSONObj indexPattern = BSON("a" << 1);
auto testIndex = buildSimpleIndexEntry(indexPattern);
- for (BSONObj obj : kNeNullQueries) {
+ for (const BSONObj& obj : kNeNullQueries) {
// It's necessary to call optimize since the $not will have a singleton $and child, which
// IndexBoundsBuilder::translate cannot handle.
auto [expr, inputParamIdMap] = parseMatchExpression(obj);
@@ -232,7 +232,7 @@ TEST_F(IndexBoundsBuilderTest,
testIndex.multikeyPaths = {MultikeyComponents{},
MultikeyComponents{0}}; // "a" is not multi-key, but "b" is.
- for (BSONObj obj : kNeNullQueries) {
+ for (const BSONObj& obj : kNeNullQueries) {
// It's necessary to call optimize since the $not will have a singleton $and child, which
// IndexBoundsBuilder::translate cannot handle.
auto [expr, inputParamIdMap] = parseMatchExpression(obj);
@@ -256,7 +256,7 @@ TEST_F(IndexBoundsBuilderTest, TranslateNotEqualToNullShouldBuildExactBoundsOnRe
BSONObj indexPattern = BSON("a" << -1);
auto testIndex = buildSimpleIndexEntry(indexPattern);
- for (BSONObj obj : kNeNullQueries) {
+ for (const BSONObj& obj : kNeNullQueries) {
// It's necessary to call optimize since the $not will have a singleton $and child, which
// IndexBoundsBuilder::translate cannot handle.
auto [expr, inputParamIdMap] = parseMatchExpression(obj);
@@ -281,7 +281,7 @@ TEST_F(IndexBoundsBuilderTest, TranslateNotEqualToNullShouldBuildInexactBoundsIf
auto testIndex = buildSimpleIndexEntry(indexPattern);
testIndex.multikey = true;
- for (BSONObj obj : kNeNullQueries) {
+ for (const BSONObj& obj : kNeNullQueries) {
// It's necessary to call optimize since the $not will have a singleton $and child, which
// IndexBoundsBuilder::translate cannot handle.
auto [expr, inputParamIdMap] = parseMatchExpression(obj);
@@ -307,7 +307,7 @@ TEST_F(IndexBoundsBuilderTest, TranslateInequalityToNullShouldProduceExactEmptyB
const std::vector<BSONObj> inequalities = {BSON("a" << BSON("$lt" << BSONNULL)),
BSON("a" << BSON("$gt" << BSONNULL))};
- for (BSONObj obj : inequalities) {
+ for (const BSONObj& obj : inequalities) {
// It's necessary to call optimize since the $not will have a singleton $and child, which
// IndexBoundsBuilder::translate cannot handle.
auto [expr, inputParamIdMap] = parseMatchExpression(obj);
@@ -333,7 +333,7 @@ TEST_F(IndexBoundsBuilderTest, TranslateNotInequalityToNullShouldProduceExactFul
BSON("a" << BSON("$not" << BSON("$lt" << BSONNULL))),
BSON("a" << BSON("$not" << BSON("$gt" << BSONNULL)))};
- for (BSONObj obj : inequalities) {
+ for (const BSONObj& obj : inequalities) {
// It's necessary to call optimize since the $not will have a singleton $and child, which
// IndexBoundsBuilder::translate cannot handle.
auto [expr, inputParamIdMap] = parseMatchExpression(obj);
@@ -363,7 +363,7 @@ TEST_F(IndexBoundsBuilderTest,
BSON("a" << BSON("$not" << BSON("$lt" << BSONNULL))),
BSON("a" << BSON("$not" << BSON("$gt" << BSONNULL)))};
- for (BSONObj obj : inequalities) {
+ for (const BSONObj& obj : inequalities) {
// It's necessary to call optimize since the $not will have a singleton $and child, which
// IndexBoundsBuilder::translate cannot handle.
auto [expr, inputParamIdMap] = parseMatchExpression(obj);
diff --git a/src/mongo/db/query/query_planner_geo_test.cpp b/src/mongo/db/query/query_planner_geo_test.cpp
index 6452f130042..4686a945ea6 100644
--- a/src/mongo/db/query/query_planner_geo_test.cpp
+++ b/src/mongo/db/query/query_planner_geo_test.cpp
@@ -1311,7 +1311,7 @@ public:
ErrorCodes::Error errorCode) {
for (auto version : versions) {
params.indices.clear();
- for (auto keyPattern : keyPatterns) {
+ for (const auto& keyPattern : keyPatterns) {
addIndex(keyPattern, BSON("2dsphereIndexVersion" << version));
}
@@ -1328,14 +1328,14 @@ public:
std::vector<std::string> expectedSolutions) {
for (auto version : versions) {
params.indices.clear();
- for (auto keyPattern : keyPatterns) {
+ for (const auto& keyPattern : keyPatterns) {
addIndex(keyPattern, BSON("2dsphereIndexVersion" << version));
}
runQuery(predicate);
assertNumSolutions(expectedSolutions.size());
- for (auto solution : expectedSolutions) {
+ for (const auto& solution : expectedSolutions) {
assertSolutionExists(solution);
}
}
@@ -1349,7 +1349,7 @@ public:
size_t numExpectedSolutions) {
for (auto version : versions) {
params.indices.clear();
- for (auto keyPattern : keyPatterns) {
+ for (const auto& keyPattern : keyPatterns) {
addIndex(keyPattern, BSON("2dsphereIndexVersion" << version));
}
diff --git a/src/mongo/db/query/sbe_stage_builder_accumulator_test.cpp b/src/mongo/db/query/sbe_stage_builder_accumulator_test.cpp
index e4fd17df36d..395840ccbbd 100644
--- a/src/mongo/db/query/sbe_stage_builder_accumulator_test.cpp
+++ b/src/mongo/db/query/sbe_stage_builder_accumulator_test.cpp
@@ -1652,7 +1652,7 @@ TEST_F(SbeStageBuilderGroupTest, SbeGroupCompatibleFlag) {
boost::intrusive_ptr<ExpressionContext> expCtx(new ExpressionContextForTest());
std::vector<BSONObj> groupSpecs;
groupSpecs.reserve(testCases.size());
- for (auto testCase : testCases) {
+ for (const auto& testCase : testCases) {
auto groupSpec = fromjson(fmt::sprintf("{%s}", testCase));
runSbeGroupCompatibleFlagTest({groupSpec}, expCtx);
groupSpecs.push_back(groupSpec);
@@ -1671,7 +1671,7 @@ TEST_F(SbeStageBuilderGroupTest, SbeIncompatibleExpressionInGroup) {
};
boost::intrusive_ptr<ExpressionContext> expCtx(new ExpressionContextForTest());
- for (auto testCase : testCases) {
+ for (const auto& testCase : testCases) {
auto groupSpec = fromjson(fmt::sprintf("{%s}", testCase));
runSbeIncompatibleGroupSpecTest({groupSpec}, expCtx);
}
diff --git a/src/mongo/db/repl/idempotency_document_structure.cpp b/src/mongo/db/repl/idempotency_document_structure.cpp
index c7869737779..4d132a77d3a 100644
--- a/src/mongo/db/repl/idempotency_document_structure.cpp
+++ b/src/mongo/db/repl/idempotency_document_structure.cpp
@@ -98,7 +98,7 @@ void DocumentStructureEnumerator::_enumerateFixedLenArrs(
nextLayerConfig.length += arr.nFields();
// Subarray.
std::vector<BSONArray> subArrs = _enumerateArrs(nextLayerConfig, scalarGenerator);
- for (auto subArr : subArrs) {
+ for (const auto& subArr : subArrs) {
BSONArrayBuilder arrayArr = _getArrayBuilderFromArr(arr);
arrayArr.append(subArr);
_enumerateFixedLenArrs(nextElementConfig, scalarGenerator, arrayArr.arr(), arrs);
@@ -109,7 +109,7 @@ void DocumentStructureEnumerator::_enumerateFixedLenArrs(
BSONObj blankDoc;
std::vector<BSONObj> subDocs;
_enumerateDocs(nextLayerConfig, scalarGenerator, blankDoc, &subDocs);
- for (auto subDoc : subDocs) {
+ for (const auto& subDoc : subDocs) {
BSONArrayBuilder docArr = _getArrayBuilderFromArr(arr);
docArr.append(subDoc);
_enumerateFixedLenArrs(nextElementConfig, scalarGenerator, docArr.arr(), arrs);
@@ -160,7 +160,7 @@ void DocumentStructureEnumerator::_enumerateDocs(const DocumentStructureEnumerat
if (!config.skipSubArrs) {
// Array.
- for (auto subArr : _enumerateArrs(nextLayerConfig, scalarGenerator)) {
+ for (const auto& subArr : _enumerateArrs(nextLayerConfig, scalarGenerator)) {
BSONObjBuilder arrayDoc(doc);
arrayDoc.append(field, subArr);
_enumerateDocs(nextFieldConfig, scalarGenerator, arrayDoc.obj(), docs);
@@ -172,7 +172,7 @@ void DocumentStructureEnumerator::_enumerateDocs(const DocumentStructureEnumerat
BSONObj blankDoc;
std::vector<BSONObj> subDocs;
_enumerateDocs(nextLayerConfig, scalarGenerator, blankDoc, &subDocs);
- for (auto subDoc : subDocs) {
+ for (const auto& subDoc : subDocs) {
BSONObjBuilder docDoc(doc);
docDoc.append(field, subDoc);
_enumerateDocs(nextFieldConfig, scalarGenerator, docDoc.obj(), docs);
diff --git a/src/mongo/db/repl/idempotency_document_structure_test.cpp b/src/mongo/db/repl/idempotency_document_structure_test.cpp
index 78870c1ad52..64bc10c0043 100644
--- a/src/mongo/db/repl/idempotency_document_structure_test.cpp
+++ b/src/mongo/db/repl/idempotency_document_structure_test.cpp
@@ -79,7 +79,7 @@ TEST(DocGenTest, SomePreChosenDocExists) {
DocumentStructureEnumerator enumerator({fields, depth, length}, &trivialScalarGenerator);
BSONObj start;
bool docFound = false;
- for (auto doc : enumerator) {
+ for (const auto& doc : enumerator) {
if (doc.binaryEqual(specialDoc)) {
docFound = true;
break;
diff --git a/src/mongo/db/repl/idempotency_test_fixture.cpp b/src/mongo/db/repl/idempotency_test_fixture.cpp
index 71c5f5f47a9..2f836b798cd 100644
--- a/src/mongo/db/repl/idempotency_test_fixture.cpp
+++ b/src/mongo/db/repl/idempotency_test_fixture.cpp
@@ -114,7 +114,7 @@ std::string CollectionState::toString() const {
sb << "Index specs: [ ";
bool firstIter = true;
- for (auto indexSpec : this->indexSpecs) {
+ for (const auto& indexSpec : this->indexSpecs) {
if (!firstIter) {
sb << ", ";
} else {
diff --git a/src/mongo/db/repl/oplog.cpp b/src/mongo/db/repl/oplog.cpp
index 4755f7d43c6..fd85fe527c0 100644
--- a/src/mongo/db/repl/oplog.cpp
+++ b/src/mongo/db/repl/oplog.cpp
@@ -1381,7 +1381,7 @@ Status applyOperation_inlock(OperationContext* opCtx,
return status;
}
wuow.commit();
- for (auto entry : insertObjs) {
+ for (size_t i = 0; i < insertObjs.size(); i++) {
opCounters->gotInsert();
if (shouldUseGlobalOpCounters) {
ServerWriteConcernMetrics::get(opCtx)->recordWriteConcernForInsert(
diff --git a/src/mongo/db/repl/oplog_applier_impl.cpp b/src/mongo/db/repl/oplog_applier_impl.cpp
index 51eebc457bc..616c184c9a9 100644
--- a/src/mongo/db/repl/oplog_applier_impl.cpp
+++ b/src/mongo/db/repl/oplog_applier_impl.cpp
@@ -642,8 +642,8 @@ StatusWith<OpTime> OplogApplierImpl::_applyOplogBatch(OperationContext* opCtx,
Timestamp firstTimeInBatch = ops.front().getTimestamp();
// Set any indexes to multikey that this batch ignored. This must be done while holding the
// parallel batch writer mode lock.
- for (WorkerMultikeyPathInfo infoVector : multikeyVector) {
- for (MultikeyPathInfo info : infoVector) {
+ for (const WorkerMultikeyPathInfo& infoVector : multikeyVector) {
+ for (const MultikeyPathInfo& info : infoVector) {
// We timestamp every multikey write with the first timestamp in the batch. It is always
// safe to set an index as multikey too early, just not too late. We conservatively pick
// the first timestamp in the batch since we do not have enough information to find out
diff --git a/src/mongo/db/repl/oplog_applier_test.cpp b/src/mongo/db/repl/oplog_applier_test.cpp
index fbd35674d1e..4ed0a224caa 100644
--- a/src/mongo/db/repl/oplog_applier_test.cpp
+++ b/src/mongo/db/repl/oplog_applier_test.cpp
@@ -331,7 +331,7 @@ TEST_F(OplogApplierTest, LastOpInLargeTransactionIsProcessedIndividually) {
// Makes entries with ts from range [2, 5).
std::vector<OplogEntry> multiEntryTransaction =
makeMultiEntryTransactionOplogEntries(2, dbName, /* prepared */ false, /* num entries*/ 3);
- for (auto entry : multiEntryTransaction) {
+ for (const auto& entry : multiEntryTransaction) {
srcOps.push_back(entry);
}
diff --git a/src/mongo/db/repl/repl_set_config_checks.cpp b/src/mongo/db/repl/repl_set_config_checks.cpp
index 883aeff59ad..1a6e39194de 100644
--- a/src/mongo/db/repl/repl_set_config_checks.cpp
+++ b/src/mongo/db/repl/repl_set_config_checks.cpp
@@ -95,10 +95,10 @@ Status ensureNoNewlyAddedMembers(const ReplSetConfig& config) {
Status validateSingleNodeChange(const ReplSetConfig& oldConfig, const ReplSetConfig& newConfig) {
// Add MemberId of voting nodes from each config into respective sets.
std::set<MemberId> oldIdSet, newIdSet;
- for (MemberConfig m : oldConfig.votingMembers()) {
+ for (const MemberConfig& m : oldConfig.votingMembers()) {
oldIdSet.insert(m.getId());
}
- for (MemberConfig m : newConfig.votingMembers()) {
+ for (const MemberConfig& m : newConfig.votingMembers()) {
newIdSet.insert(m.getId());
}
diff --git a/src/mongo/db/repl/replication_consistency_markers_impl.cpp b/src/mongo/db/repl/replication_consistency_markers_impl.cpp
index e048d6e36e8..b06238cb0d9 100644
--- a/src/mongo/db/repl/replication_consistency_markers_impl.cpp
+++ b/src/mongo/db/repl/replication_consistency_markers_impl.cpp
@@ -492,7 +492,8 @@ ReplicationConsistencyMarkersImpl::refreshOplogTruncateAfterPointIfPrimary(
}
Status ReplicationConsistencyMarkersImpl::createInternalCollections(OperationContext* opCtx) {
- for (auto nss : std::vector<NamespaceString>({_oplogTruncateAfterPointNss, _minValidNss})) {
+ for (const auto& nss :
+ std::vector<NamespaceString>({_oplogTruncateAfterPointNss, _minValidNss})) {
auto status = _storageInterface->createCollection(opCtx, nss, CollectionOptions());
if (!status.isOK() && status.code() != ErrorCodes::NamespaceExists) {
return {ErrorCodes::CannotCreateCollection,
diff --git a/src/mongo/db/repl/replication_coordinator_impl_heartbeat.cpp b/src/mongo/db/repl/replication_coordinator_impl_heartbeat.cpp
index 4dfa56bf965..4c2828769be 100644
--- a/src/mongo/db/repl/replication_coordinator_impl_heartbeat.cpp
+++ b/src/mongo/db/repl/replication_coordinator_impl_heartbeat.cpp
@@ -1146,7 +1146,7 @@ void ReplicationCoordinatorImpl::_restartScheduledHeartbeats_inlock(
restartedTargets.insert(hbHandle.target);
}
- for (auto target : restartedTargets) {
+ for (const auto& target : restartedTargets) {
_scheduleHeartbeatToTarget_inlock(target, now, replSetName);
_topCoord->restartHeartbeat(now, target);
}
diff --git a/src/mongo/db/repl/replication_coordinator_impl_heartbeat_v1_test.cpp b/src/mongo/db/repl/replication_coordinator_impl_heartbeat_v1_test.cpp
index 6457bb95e71..447f79c90d5 100644
--- a/src/mongo/db/repl/replication_coordinator_impl_heartbeat_v1_test.cpp
+++ b/src/mongo/db/repl/replication_coordinator_impl_heartbeat_v1_test.cpp
@@ -1112,7 +1112,7 @@ TEST_F(ReplCoordHBV1ReconfigTest,
// from the config object. This simulates the case of receiving a heartbeat response from a 4.2
// node.
BSONObjBuilder finalRes;
- for (auto field : origResObj.getFieldNames<std::set<std::string>>()) {
+ for (const auto& field : origResObj.getFieldNames<std::set<std::string>>()) {
if (field == "t") {
continue;
} else if (field == "config") {
diff --git a/src/mongo/db/repl/replication_coordinator_impl_test.cpp b/src/mongo/db/repl/replication_coordinator_impl_test.cpp
index 82bb25ea9fb..061990d820b 100644
--- a/src/mongo/db/repl/replication_coordinator_impl_test.cpp
+++ b/src/mongo/db/repl/replication_coordinator_impl_test.cpp
@@ -1712,7 +1712,7 @@ TEST_F(ReplCoordTest, UpdatePositionArgsAdvancesWallTimes) {
// Make sure wall times are propagated through processReplSetUpdatePosition
auto memberDataVector = repl->getMemberData();
- for (auto member : memberDataVector) {
+ for (const auto& member : memberDataVector) {
if (member.getMemberId() == MemberId(1)) {
ASSERT_EQ(member.getLastAppliedWallTime(), memberOneAppliedWallTime);
ASSERT_EQ(member.getLastDurableWallTime(), memberOneDurableWallTime);
@@ -8372,7 +8372,7 @@ TEST_F(ReplCoordTest, IgnoreNonNullDurableOpTimeOrWallTimeForArbiterFromReplSetU
// Make sure node 2 is fully caught up but node 3 has null durable optime/walltime.
auto memberDataVector = repl->getMemberData();
- for (auto member : memberDataVector) {
+ for (const auto& member : memberDataVector) {
auto memberId = member.getMemberId();
if (memberId == MemberId(1) || memberId == MemberId(2)) {
ASSERT_EQ(member.getLastAppliedOpTime(), opTime2.asOpTime());
@@ -8441,7 +8441,7 @@ TEST_F(ReplCoordTest, IgnoreNonNullDurableOpTimeOrWallTimeForArbiterFromHeartbea
hbResp.toBSON(), 1 /* targetIndex */, Milliseconds(5) /* ping */);
auto memberDataVector = repl->getMemberData();
- for (auto member : memberDataVector) {
+ for (const auto& member : memberDataVector) {
auto memberId = member.getMemberId();
if (memberId == MemberId(1)) {
ASSERT_EQ(member.getLastAppliedOpTime(), opTime2.asOpTime());
diff --git a/src/mongo/db/repl/rs_rollback.cpp b/src/mongo/db/repl/rs_rollback.cpp
index c652807fb08..38f439db49a 100644
--- a/src/mongo/db/repl/rs_rollback.cpp
+++ b/src/mongo/db/repl/rs_rollback.cpp
@@ -1351,7 +1351,7 @@ void syncFixUp(OperationContext* opCtx,
// collection drops, because one of the preconditions of dropping a collection is that there are
// no unfinished indxes.
LOGV2(21694, "Rolling back unfinished startIndexBuild operations");
- for (auto index : fixUpInfo.unfinishedIndexesToDrop) {
+ for (const auto& index : fixUpInfo.unfinishedIndexesToDrop) {
UUID uuid = index.first;
std::set<std::string> indexNames = index.second;
diff --git a/src/mongo/db/repl/tenant_migration_recipient_service_test.cpp b/src/mongo/db/repl/tenant_migration_recipient_service_test.cpp
index 0452db238ac..a001755861f 100644
--- a/src/mongo/db/repl/tenant_migration_recipient_service_test.cpp
+++ b/src/mongo/db/repl/tenant_migration_recipient_service_test.cpp
@@ -2081,12 +2081,12 @@ TEST_F(TenantMigrationRecipientServiceTest,
collUuid,
entryAfterStartApplyingOpTime,
boost::none /* migrationUUID */));
- for (auto entry : oplogEntries) {
+ for (const auto& entry : oplogEntries) {
auto opTime = entry.getOpTime();
ASSERT_OK(storage->insertDocument(
opCtx.get(), oplogNss, {entry.toBSON(), opTime.getTimestamp()}, opTime.getTerm()));
}
- for (auto entry : noOpEntries) {
+ for (const auto& entry : noOpEntries) {
auto opTime = entry.getOpTime();
ASSERT_OK(storage->insertDocument(
opCtx.get(), oplogNss, {entry.toBSON(), opTime.getTimestamp()}, opTime.getTerm()));
@@ -2229,7 +2229,7 @@ TEST_F(TenantMigrationRecipientServiceTest, OplogApplierResumesFromStartDonorApp
entryAfterStartApplyingOpTime,
boost::none /* migrationUUID */);
- for (auto entry : oplogEntries) {
+ for (const auto& entry : oplogEntries) {
auto opTime = entry.getOpTime();
ASSERT_OK(storage->insertDocument(
opCtx.get(), oplogNss, {entry.toBSON(), opTime.getTimestamp()}, opTime.getTerm()));
diff --git a/src/mongo/db/repl/tenant_oplog_batcher_test.cpp b/src/mongo/db/repl/tenant_oplog_batcher_test.cpp
index e7e1e4791a8..970c444cdd0 100644
--- a/src/mongo/db/repl/tenant_oplog_batcher_test.cpp
+++ b/src/mongo/db/repl/tenant_oplog_batcher_test.cpp
@@ -336,7 +336,7 @@ TEST_F(TenantOplogBatcherTest, LargeTransactionProcessedIndividuallyAndExpanded)
// Makes entries with ts from range [2, 5).
std::vector<OplogEntry> multiEntryTransaction = makeMultiEntryTransactionOplogEntries(
2, dbName, /* prepared */ false, {innerOps1, innerOps2, innerOps3});
- for (auto entry : multiEntryTransaction) {
+ for (const auto& entry : multiEntryTransaction) {
srcOps.push_back(entry.getEntry().toBSON());
}
diff --git a/src/mongo/db/s/config/initial_split_policy.cpp b/src/mongo/db/s/config/initial_split_policy.cpp
index ec76b8b13a9..791d39061d5 100644
--- a/src/mongo/db/s/config/initial_split_policy.cpp
+++ b/src/mongo/db/s/config/initial_split_policy.cpp
@@ -764,7 +764,7 @@ BSONObjSet ReshardingSplitPolicy::_extractSplitPointsFromZones(const ShardKeyPat
return splitPoints;
}
- for (auto zone : *_zones) {
+ for (const auto& zone : *_zones) {
splitPoints.insert(zone.getMinKey());
splitPoints.insert(zone.getMaxKey());
}
diff --git a/src/mongo/db/s/config/sharding_catalog_manager_config_initialization_test.cpp b/src/mongo/db/s/config/sharding_catalog_manager_config_initialization_test.cpp
index b9f56a5d64a..3af87160948 100644
--- a/src/mongo/db/s/config/sharding_catalog_manager_config_initialization_test.cpp
+++ b/src/mongo/db/s/config/sharding_catalog_manager_config_initialization_test.cpp
@@ -215,7 +215,7 @@ TEST_F(ConfigInitializationTest, ReRunsIfDocRolledBackThenReElected) {
recordIds.push_back(recordId->id);
}
mongo::WriteUnitOfWork wuow(opCtx);
- for (auto recordId : recordIds) {
+ for (const auto& recordId : recordIds) {
coll->deleteDocument(opCtx, kUninitializedStmtId, recordId, nullptr);
}
wuow.commit();
diff --git a/src/mongo/db/s/config/sharding_catalog_manager_remove_shard_test.cpp b/src/mongo/db/s/config/sharding_catalog_manager_remove_shard_test.cpp
index 7a03900dd42..37da8bfe872 100644
--- a/src/mongo/db/s/config/sharding_catalog_manager_remove_shard_test.cpp
+++ b/src/mongo/db/s/config/sharding_catalog_manager_remove_shard_test.cpp
@@ -334,7 +334,7 @@ TEST_F(RemoveShardTest, RemoveShardCompletion) {
// Mock the operation during which the chunks are moved to the other shard.
const NamespaceString chunkNS(ChunkType::ConfigNS);
- for (ChunkType chunk : chunks) {
+ for (const ChunkType& chunk : chunks) {
ChunkType updatedChunk = chunk;
updatedChunk.setShard(shard2.getName());
ASSERT_OK(updateToConfigCollection(
diff --git a/src/mongo/db/s/migration_chunk_cloner_source_legacy_test.cpp b/src/mongo/db/s/migration_chunk_cloner_source_legacy_test.cpp
index 6ffb1547204..d9e965e366f 100644
--- a/src/mongo/db/s/migration_chunk_cloner_source_legacy_test.cpp
+++ b/src/mongo/db/s/migration_chunk_cloner_source_legacy_test.cpp
@@ -590,7 +590,7 @@ TEST_F(MigrationChunkClonerSourceLegacyTest, ManySmallDocumentsTransferMods) {
}
WriteUnitOfWork wuow(operationContext());
- for (BSONObj add : insertDocs) {
+ for (const BSONObj& add : insertDocs) {
cloner.onInsertOp(operationContext(), add, {});
}
wuow.commit();
diff --git a/src/mongo/db/s/resharding/resharding_util.cpp b/src/mongo/db/s/resharding/resharding_util.cpp
index 5e3721c89f2..e0f050409c6 100644
--- a/src/mongo/db/s/resharding/resharding_util.cpp
+++ b/src/mongo/db/s/resharding/resharding_util.cpp
@@ -167,7 +167,7 @@ void checkForHolesAndOverlapsInChunks(std::vector<ReshardedChunk>& chunks,
keyPattern.globalMax()));
boost::optional<BSONObj> prevMax = boost::none;
- for (auto chunk : chunks) {
+ for (const auto& chunk : chunks) {
if (prevMax) {
uassert(ErrorCodes::BadValue,
"Chunk ranges must be contiguous",
@@ -213,7 +213,7 @@ void checkForOverlappingZones(std::vector<ReshardingZoneType>& zones) {
});
boost::optional<BSONObj> prevMax = boost::none;
- for (auto zone : zones) {
+ for (const auto& zone : zones) {
if (prevMax) {
uassert(ErrorCodes::BadValue,
"Zone ranges must not overlap",
diff --git a/src/mongo/db/s/session_catalog_migration_source_test.cpp b/src/mongo/db/s/session_catalog_migration_source_test.cpp
index 69a35c7e9ae..49c40b93d3c 100644
--- a/src/mongo/db/s/session_catalog_migration_source_test.cpp
+++ b/src/mongo/db/s/session_catalog_migration_source_test.cpp
@@ -579,7 +579,7 @@ TEST_F(SessionCatalogMigrationSourceTest, OneSessionWithFindAndModifyPreImageAnd
auto expectedSequence = {entry3, entry4, entry1, entry2};
- for (auto oplog : expectedSequence) {
+ for (const auto& oplog : expectedSequence) {
ASSERT_TRUE(migrationSource.hasMoreOplog());
auto nextOplogResult = migrationSource.getLastFetchedOplog();
ASSERT_FALSE(nextOplogResult.shouldWaitForMajority);
@@ -661,7 +661,7 @@ TEST_F(SessionCatalogMigrationSourceTest,
auto expectedSequence = {entry3, entry4, entry1, entry2};
- for (auto oplog : expectedSequence) {
+ for (const auto& oplog : expectedSequence) {
ASSERT_TRUE(migrationSource.hasMoreOplog());
auto nextOplogResult = migrationSource.getLastFetchedOplog();
ASSERT_FALSE(nextOplogResult.shouldWaitForMajority);
@@ -2354,7 +2354,7 @@ TEST_F(SessionCatalogMigrationSourceTest,
auto expectedSequence = {entry1, entry2};
- for (auto oplog : expectedSequence) {
+ for (const auto& oplog : expectedSequence) {
ASSERT_TRUE(migrationSource.hasMoreOplog());
auto nextOplogResult = migrationSource.getLastFetchedOplog();
ASSERT_FALSE(nextOplogResult.shouldWaitForMajority);
@@ -2535,7 +2535,7 @@ TEST_F(SessionCatalogMigrationSourceTest, TwoSessionWithTwoWritesContainingWrite
auto expectedSequence = {entry1a, entry2b, entry2a};
- for (auto oplog : expectedSequence) {
+ for (const auto& oplog : expectedSequence) {
ASSERT_TRUE(migrationSource.hasMoreOplog());
auto nextOplogResult = migrationSource.getLastFetchedOplog();
ASSERT_FALSE(nextOplogResult.shouldWaitForMajority);
@@ -2682,7 +2682,7 @@ TEST_F(SessionCatalogMigrationSourceTest, FilterRewrittenOplogEntriesOutsideChun
DBDirectClient client(opCtx());
- for (auto entry : entries) {
+ for (const auto& entry : entries) {
SessionTxnRecord sessionRecord(
sessionId, txnNumber, entry.getOpTime(), entry.getWallClockTime());
@@ -2732,7 +2732,7 @@ TEST_F(SessionCatalogMigrationSourceTest,
client.insert(NamespaceString::kSessionTransactionsTableNamespace.ns(),
sessionRecord1.toBSON());
- for (auto entry : entries) {
+ for (const auto& entry : entries) {
insertOplogEntry(entry);
}
diff --git a/src/mongo/db/s/sharding_ddl_util.cpp b/src/mongo/db/s/sharding_ddl_util.cpp
index ba16739d2ff..5beca502d6a 100644
--- a/src/mongo/db/s/sharding_ddl_util.cpp
+++ b/src/mongo/db/s/sharding_ddl_util.cpp
@@ -195,7 +195,7 @@ void checkCollectionUUIDConsistencyAcrossShards(
std::vector<MismatchedShard> mismatches;
- for (auto cmdResponse : responses) {
+ for (const auto& cmdResponse : responses) {
auto responseData = uassertStatusOK(cmdResponse.swResponse);
auto collectionVector = responseData.data.firstElement()["firstBatch"].Array();
auto shardId = cmdResponse.shardId;
@@ -217,7 +217,7 @@ void checkCollectionUUIDConsistencyAcrossShards(
<< " with expected UUID: " << collectionUuid.toString()
<< " has different UUIDs on the following shards: [";
- for (auto mismatch : mismatches) {
+ for (const auto& mismatch : mismatches) {
errorMessage << "{ " << mismatch.shardId << ":" << mismatch.uuid << " },";
}
errorMessage << "]";
@@ -239,7 +239,7 @@ void checkTargetCollectionDoesNotExistInCluster(
opCtx, toNss.db(), cmdObj, shardIds, **executor);
std::vector<std::string> shardsContainingTargetCollection;
- for (auto cmdResponse : responses) {
+ for (const auto& cmdResponse : responses) {
uassertStatusOK(cmdResponse.swResponse);
auto responseData = uassertStatusOK(cmdResponse.swResponse);
auto collectionVector = responseData.data.firstElement()["firstBatch"].Array();
diff --git a/src/mongo/db/s/shardsvr_abort_reshard_collection_command.cpp b/src/mongo/db/s/shardsvr_abort_reshard_collection_command.cpp
index f0918cc5766..79361b0797f 100644
--- a/src/mongo/db/s/shardsvr_abort_reshard_collection_command.cpp
+++ b/src/mongo/db/s/shardsvr_abort_reshard_collection_command.cpp
@@ -92,7 +92,7 @@ public:
(*machine)->abort(isUserCanceled());
}
- for (auto doneFuture : futuresToWait) {
+ for (const auto& doneFuture : futuresToWait) {
doneFuture.get(opCtx);
}
diff --git a/src/mongo/db/s/shardsvr_commit_reshard_collection_command.cpp b/src/mongo/db/s/shardsvr_commit_reshard_collection_command.cpp
index 3d9be030fcb..a7cd3bbff19 100644
--- a/src/mongo/db/s/shardsvr_commit_reshard_collection_command.cpp
+++ b/src/mongo/db/s/shardsvr_commit_reshard_collection_command.cpp
@@ -100,7 +100,7 @@ public:
}
}
- for (auto doneFuture : futuresToWait) {
+ for (const auto& doneFuture : futuresToWait) {
doneFuture.get(opCtx);
}
diff --git a/src/mongo/db/serverless/shard_split_donor_service_test.cpp b/src/mongo/db/serverless/shard_split_donor_service_test.cpp
index 743f64669c8..463031b66bc 100644
--- a/src/mongo/db/serverless/shard_split_donor_service_test.cpp
+++ b/src/mongo/db/serverless/shard_split_donor_service_test.cpp
@@ -480,7 +480,7 @@ auto makeHelloReply(const std::string& setName,
};
void mockCommandReplies(MockReplicaSet* replSet) {
- for (auto hostAndPort : replSet->getHosts()) {
+ for (const auto& hostAndPort : replSet->getHosts()) {
auto node = replSet->getNode(hostAndPort.toString());
node->setCommandReply("replSetStepUp", BSON("ok" << 1));
node->setCommandReply("appendOplogNote", BSON("ok" << 1));
diff --git a/src/mongo/db/serverless/shard_split_test_utils.cpp b/src/mongo/db/serverless/shard_split_test_utils.cpp
index 0593fa54053..5570ae6113a 100644
--- a/src/mongo/db/serverless/shard_split_test_utils.cpp
+++ b/src/mongo/db/serverless/shard_split_test_utils.cpp
@@ -58,10 +58,10 @@ void reconfigToAddRecipientNodes(ServiceContext* serviceContext,
const std::vector<HostAndPort>& recipientNodes) {
BSONArrayBuilder members;
int idx = 0;
- for (auto node : donorNodes) {
+ for (const auto& node : donorNodes) {
members.append(BSON("_id" << idx++ << "host" << node.toString()));
}
- for (auto node : recipientNodes) {
+ for (const auto& node : recipientNodes) {
members.append(BSON("_id" << idx++ << "host" << node.toString() << "priority" << 0
<< "hidden" << 1 << "votes" << 0 << "tags"
<< BSON(recipientTagName << UUID::gen().toString())));
diff --git a/src/mongo/db/serverless/shard_split_utils.cpp b/src/mongo/db/serverless/shard_split_utils.cpp
index 465e32826ce..2168526b22b 100644
--- a/src/mongo/db/serverless/shard_split_utils.cpp
+++ b/src/mongo/db/serverless/shard_split_utils.cpp
@@ -253,7 +253,7 @@ Status validateRecipientNodesForShardSplit(const ShardSplitDonorDocument& stateD
stdx::unordered_set<std::string> uniqueTagValues;
const auto& tagConfig = localConfig.getTagConfig();
- for (auto member : recipientNodes) {
+ for (const auto& member : recipientNodes) {
for (repl::MemberConfig::TagIterator it = member.tagsBegin(); it != member.tagsEnd();
++it) {
if (tagConfig.getTagKey(*it) == *recipientTagName) {
diff --git a/src/mongo/db/storage/key_string_bm.cpp b/src/mongo/db/storage/key_string_bm.cpp
index bb500fc0a45..4e8b45c4818 100644
--- a/src/mongo/db/storage/key_string_bm.cpp
+++ b/src/mongo/db/storage/key_string_bm.cpp
@@ -127,7 +127,7 @@ void BM_BSONToKeyString(benchmark::State& state,
const BsonsAndKeyStrings bsonsAndKeyStrings = generateBsonsAndKeyStrings(bsonType, version);
for (auto _ : state) {
benchmark::ClobberMemory();
- for (auto bson : bsonsAndKeyStrings.bsons) {
+ for (const auto& bson : bsonsAndKeyStrings.bsons) {
benchmark::DoNotOptimize(KeyString::Builder(version, bson, ALL_ASCENDING));
}
}
diff --git a/src/mongo/db/storage/key_string_test.cpp b/src/mongo/db/storage/key_string_test.cpp
index 733e527243f..d1ae1b3cda3 100644
--- a/src/mongo/db/storage/key_string_test.cpp
+++ b/src/mongo/db/storage/key_string_test.cpp
@@ -1847,7 +1847,7 @@ TEST_F(KeyStringBuilderTest, RandomizedInputsForToBsonSafe) {
std::numeric_limits<unsigned int>::max());
const auto interestingElements = getInterestingElements(KeyString::Version::V1);
- for (auto elem : interestingElements) {
+ for (const auto& elem : interestingElements) {
const KeyString::Builder ks(KeyString::Version::V1, elem, ALL_ASCENDING);
auto ksBuffer = SharedBuffer::allocate(ks.getSize());
@@ -1908,7 +1908,7 @@ void perfTest(KeyString::Version version, const Numbers& numbers) {
Timer t;
for (uint64_t i = 0; i < iters; i++)
- for (auto item : numbers) {
+ for (const auto& item : numbers) {
// Assuming there are sufficient invariants in the to/from KeyString::Builder
// methods
// that calls will not be optimized away.
diff --git a/src/mongo/db/storage/storage_engine_impl.cpp b/src/mongo/db/storage/storage_engine_impl.cpp
index 66a4e36183b..2743c014c96 100644
--- a/src/mongo/db/storage/storage_engine_impl.cpp
+++ b/src/mongo/db/storage/storage_engine_impl.cpp
@@ -654,7 +654,7 @@ StatusWith<StorageEngine::ReconcileResult> StorageEngineImpl::reconcileCatalogAn
// other contexts such as `recoverToStableTimestamp`.
std::vector<DurableCatalog::Entry> catalogEntries = _catalog->getAllCatalogEntries(opCtx);
if (!_options.forRepair) {
- for (DurableCatalog::Entry entry : catalogEntries) {
+ for (const DurableCatalog::Entry& entry : catalogEntries) {
if (engineIdents.find(entry.ident) == engineIdents.end()) {
return {ErrorCodes::UnrecoverableRollbackError,
str::stream() << "Expected collection does not exist. Collection: "
@@ -668,7 +668,7 @@ StatusWith<StorageEngine::ReconcileResult> StorageEngineImpl::reconcileCatalogAn
//
// Also, remove unfinished builds except those that were background index builds started on a
// secondary.
- for (DurableCatalog::Entry entry : catalogEntries) {
+ for (const DurableCatalog::Entry& entry : catalogEntries) {
std::shared_ptr<BSONCollectionCatalogEntry::MetaData> metaData =
_catalog->getMetaData(opCtx, entry.catalogId);
NamespaceString nss(metaData->nss);
diff --git a/src/mongo/db/storage/wiredtiger/wiredtiger_util.cpp b/src/mongo/db/storage/wiredtiger/wiredtiger_util.cpp
index 855a56b6bd0..7ce4cd12e34 100644
--- a/src/mongo/db/storage/wiredtiger/wiredtiger_util.cpp
+++ b/src/mongo/db/storage/wiredtiger/wiredtiger_util.cpp
@@ -436,7 +436,7 @@ Status WiredTigerUtil::checkTableCreationOptions(const BSONElement& configElem)
if (!status.isOK()) {
StringBuilder errorMsg;
errorMsg << status.reason();
- for (std::string error : errors) {
+ for (const std::string& error : errors) {
errorMsg << ". " << error;
}
errorMsg << ".";
diff --git a/src/mongo/db/timeseries/bucket_catalog_helpers_test.cpp b/src/mongo/db/timeseries/bucket_catalog_helpers_test.cpp
index 4c85c9133f7..54356c1cd1f 100644
--- a/src/mongo/db/timeseries/bucket_catalog_helpers_test.cpp
+++ b/src/mongo/db/timeseries/bucket_catalog_helpers_test.cpp
@@ -366,7 +366,7 @@ TEST_F(BucketCatalogHelpersTest, FindSuitableBucketForMeasurements) {
// no meta field specified.
{
std::vector<BSONObj> docsWithOutMeta;
- for (auto doc : docsWithSuitableBuckets) {
+ for (const auto& doc : docsWithSuitableBuckets) {
docsWithOutMeta.push_back(doc.removeField(_metaField));
}
diff --git a/src/mongo/dbtests/query_stage_batched_delete.cpp b/src/mongo/dbtests/query_stage_batched_delete.cpp
index 426f0d53e66..be980ae883b 100644
--- a/src/mongo/dbtests/query_stage_batched_delete.cpp
+++ b/src/mongo/dbtests/query_stage_batched_delete.cpp
@@ -120,7 +120,7 @@ public:
void insertTimedBatch(std::vector<std::pair<BSONObj, Milliseconds>> timedBatch,
bool verifyBatchTimeWithDefaultTargetBatchTimeMS = true) {
Milliseconds totalDurationOfBatch{0};
- for (auto [doc, duration] : timedBatch) {
+ for (const auto& [doc, duration] : timedBatch) {
_client.insert(nss.ns(), doc);
_opObserver->setDeleteRecordDurationMillis(doc, duration);
totalDurationOfBatch += duration;
diff --git a/src/mongo/dbtests/query_stage_collscan.cpp b/src/mongo/dbtests/query_stage_collscan.cpp
index fa180a525b6..35d0b8d5024 100644
--- a/src/mongo/dbtests/query_stage_collscan.cpp
+++ b/src/mongo/dbtests/query_stage_collscan.cpp
@@ -756,7 +756,7 @@ TEST_F(QueryStageCollectionScanTest, QueryTestCollscanClusteredMinMaxDateExclusi
Date_t minDate = middleDate - Milliseconds(1);
std::vector<BSONObj> dateDocuments = {
BSON("_id" << minDate), BSON("_id" << middleDate), BSON("_id" << maxDate)};
- for (auto doc : dateDocuments) {
+ for (const auto& doc : dateDocuments) {
insertDocument(ns, doc);
}
diff --git a/src/mongo/dbtests/query_stage_trial.cpp b/src/mongo/dbtests/query_stage_trial.cpp
index 00f7bdbcfa9..72437204c7e 100644
--- a/src/mongo/dbtests/query_stage_trial.cpp
+++ b/src/mongo/dbtests/query_stage_trial.cpp
@@ -56,7 +56,7 @@ protected:
// Pushes BSONObjs from the given vector into the given MockStage. Each empty BSONObj in
// the vector causes a NEED_TIME to be queued up at that point instead of a result.
void queueData(const std::vector<BSONObj>& results, MockStage* mockStage) {
- for (auto result : results) {
+ for (const auto& result : results) {
if (result.isEmpty()) {
mockStage->enqueueStateCode(PlanStage::NEED_TIME);
continue;
@@ -130,7 +130,7 @@ TEST_F(TrialStageTest, AdoptsTrialPlanIfTrialSucceeds) {
ASSERT_FALSE(trialStage->pickedBackupPlan());
// Confirm that we see the full trialPlan results when we iterate the trialStage.
- for (auto result : trialResults) {
+ for (const auto& result : trialResults) {
ASSERT_BSONOBJ_EQ(result, *nextResult(trialStage.get()));
}
ASSERT_FALSE(nextResult(trialStage.get()));
@@ -165,7 +165,7 @@ TEST_F(TrialStageTest, AdoptsTrialPlanIfTrialPlanHitsEOF) {
ASSERT_EQ(stats->trialWorks, 5U);
// Confirm that we see the full trialPlan results when we iterate the trialStage.
- for (auto result : trialResults) {
+ for (const auto& result : trialResults) {
ASSERT_BSONOBJ_EQ(result, *nextResult(trialStage.get()));
}
ASSERT_FALSE(nextResult(trialStage.get()));
@@ -203,7 +203,7 @@ TEST_F(TrialStageTest, AdoptsBackupPlanIfTrialDoesNotSucceed) {
ASSERT_TRUE(trialStage->pickedBackupPlan());
// Confirm that we see the full backupPlan results when we iterate the trialStage.
- for (auto result : backupResults) {
+ for (const auto& result : backupResults) {
ASSERT_BSONOBJ_EQ(result, *nextResult(trialStage.get()));
}
ASSERT_FALSE(nextResult(trialStage.get()));
diff --git a/src/mongo/dbtests/querytests.cpp b/src/mongo/dbtests/querytests.cpp
index 677764e3d3b..fa8ff99ae97 100644
--- a/src/mongo/dbtests/querytests.cpp
+++ b/src/mongo/dbtests/querytests.cpp
@@ -1815,7 +1815,7 @@ public:
void checkNewDBInResults(const std::vector<BSONObj> results, const int dbNum) {
std::string target = "unittestsdb" + std::to_string(dbNum);
- for (auto res : results) {
+ for (const auto& res : results) {
if (res["name"].str() == target) {
return;
}
diff --git a/src/mongo/executor/task_executor_cursor_integration_test.cpp b/src/mongo/executor/task_executor_cursor_integration_test.cpp
index d4ecc626602..2f10dd39aaa 100644
--- a/src/mongo/executor/task_executor_cursor_integration_test.cpp
+++ b/src/mongo/executor/task_executor_cursor_integration_test.cpp
@@ -184,7 +184,7 @@ TEST_F(TaskExecutorCursorFixture, ConnectionRemainsOpenAfterKillingTheCursor) {
for (size_t i = 0; i < kNumConnections; i++) {
handles.emplace_back(scheduleRemoteCommand(opCtx.get(), target, cmd));
}
- for (auto cbHandle : handles) {
+ for (const auto& cbHandle : handles) {
executor()->wait(cbHandle);
}
diff --git a/src/mongo/executor/task_executor_test_common.cpp b/src/mongo/executor/task_executor_test_common.cpp
index 43cc6687175..98a68a837fe 100644
--- a/src/mongo/executor/task_executor_test_common.cpp
+++ b/src/mongo/executor/task_executor_test_common.cpp
@@ -1113,7 +1113,7 @@ COMMON_EXECUTOR_TEST(ScheduleExhaustRemoteCommandFutureIsResolvedWithErrorOnCanc
void addTestsForExecutor(const std::string& suiteName, ExecutorFactory makeExecutor) {
auto& suite = unittest::Suite::getSuite(suiteName);
- for (auto testCase : executorTestCaseRegistry()) {
+ for (const auto& testCase : executorTestCaseRegistry()) {
suite.add(str::stream() << suiteName << "::" << testCase.first,
__FILE__,
[testCase, makeExecutor] { testCase.second(makeExecutor)->run(); });
diff --git a/src/mongo/logv2/redaction_test.cpp b/src/mongo/logv2/redaction_test.cpp
index fe3d9f56b2f..7c9640c8fa8 100644
--- a/src/mongo/logv2/redaction_test.cpp
+++ b/src/mongo/logv2/redaction_test.cpp
@@ -51,7 +51,7 @@ TEST(RedactStringTest, NoRedact) {
logv2::setShouldRedactLogs(false);
std::string toRedact[] = {"", "abc", "*&$@!_\\\\\\\"*&$@!_\"*&$@!_\"*&$@!_"};
- for (auto s : toRedact) {
+ for (const auto& s : toRedact) {
ASSERT_EQ(redact(s), s);
}
}
@@ -60,7 +60,7 @@ TEST(RedactStringTest, BasicStrings) {
logv2::setShouldRedactLogs(true);
std::string toRedact[] = {"", "abc", "*&$@!_\\\\\\\"*&$@!_\"*&$@!_\"*&$@!_"};
- for (auto s : toRedact) {
+ for (const auto& s : toRedact) {
ASSERT_EQ(redact(s), kRedactionDefaultMask);
}
}
@@ -104,7 +104,7 @@ TEST(RedactBSONTest, NoRedact) {
}
void testBSONCases(std::initializer_list<BSONStringPair> testCases) {
- for (auto m : testCases) {
+ for (const auto& m : testCases) {
ASSERT_EQ(redact(m.first).toString(), m.second);
}
}
@@ -152,7 +152,7 @@ TEST(RedactEncryptedStringTest, BasicStrings) {
}
void testBSONCases(std::vector<BSONStringPair>& testCases) {
- for (auto m : testCases) {
+ for (const auto& m : testCases) {
ASSERT_EQ(redact(m.first).toString(), m.second);
}
}
diff --git a/src/mongo/rpc/metadata_test.cpp b/src/mongo/rpc/metadata_test.cpp
index 898b98c745a..6cfa75f14e5 100644
--- a/src/mongo/rpc/metadata_test.cpp
+++ b/src/mongo/rpc/metadata_test.cpp
@@ -181,7 +181,7 @@ TEST(Metadata, UpconvertUsesDocumentSequecesCorrectly) {
fromjson("{NOT_insert: 'coll', documents:[{a:1}]}"),
};
- for (auto cmd : valid) {
+ for (const auto& cmd : valid) {
const auto converted = rpc::upconvertRequest("db", cmd, 0);
ASSERT_BSONOBJ_EQ(converted.body, fromjson("{insert: 'coll', $db: 'db'}"));
ASSERT_EQ(converted.sequences.size(), 1u);
@@ -203,7 +203,7 @@ TEST(Metadata, UpconvertUsesDocumentSequecesCorrectly) {
}
}
- for (auto cmd : invalid) {
+ for (const auto& cmd : invalid) {
const auto converted = rpc::upconvertRequest("db", cmd, 0);
ASSERT_BSONOBJ_EQ(converted.body, addDollarDB(cmd, "db"));
ASSERT_EQ(converted.sequences.size(), 0u);
diff --git a/src/mongo/s/multi_statement_transaction_requests_sender.cpp b/src/mongo/s/multi_statement_transaction_requests_sender.cpp
index c62b4e97da4..95849499a04 100644
--- a/src/mongo/s/multi_statement_transaction_requests_sender.cpp
+++ b/src/mongo/s/multi_statement_transaction_requests_sender.cpp
@@ -49,7 +49,7 @@ std::vector<AsyncRequestsSender::Request> attachTxnDetails(
std::vector<AsyncRequestsSender::Request> newRequests;
newRequests.reserve(requests.size());
- for (auto request : requests) {
+ for (const auto& request : requests) {
newRequests.emplace_back(
request.shardId,
txnRouter.attachTxnFieldsIfNeeded(opCtx, request.shardId, request.cmdObj));
diff --git a/src/mongo/s/transaction_router_test.cpp b/src/mongo/s/transaction_router_test.cpp
index d6f1d93d133..d6e26b2d436 100644
--- a/src/mongo/s/transaction_router_test.cpp
+++ b/src/mongo/s/transaction_router_test.cpp
@@ -2567,7 +2567,7 @@ TEST_F(TransactionRouterTestWithDefaultSession,
TEST_F(TransactionRouterTestWithDefaultSession, NonSnapshotReadConcernHasNoAtClusterTime) {
TxnNumber txnNum{3};
- for (auto rcIt : supportedNonSnapshotRCLevels) {
+ for (const auto& rcIt : supportedNonSnapshotRCLevels) {
repl::ReadConcernArgs::get(operationContext()) = repl::ReadConcernArgs(rcIt.second);
auto txnRouter = TransactionRouter::get(operationContext());
@@ -2589,7 +2589,7 @@ TEST_F(TransactionRouterTestWithDefaultSession, NonSnapshotReadConcernHasNoAtClu
TEST_F(TransactionRouterTestWithDefaultSession,
SupportedNonSnapshotReadConcernLevelsArePassedThrough) {
TxnNumber txnNum{3};
- for (auto rcIt : supportedNonSnapshotRCLevels) {
+ for (const auto& rcIt : supportedNonSnapshotRCLevels) {
repl::ReadConcernArgs::get(operationContext()) = repl::ReadConcernArgs(rcIt.second);
auto txnRouter = TransactionRouter::get(operationContext());
@@ -2624,7 +2624,7 @@ TEST_F(TransactionRouterTestWithDefaultSession,
NonSnapshotReadConcernLevelsPreserveAfterClusterTime) {
const auto clusterTime = LogicalTime(Timestamp(10, 1));
TxnNumber txnNum{3};
- for (auto rcIt : supportedNonSnapshotRCLevels) {
+ for (const auto& rcIt : supportedNonSnapshotRCLevels) {
repl::ReadConcernArgs::get(operationContext()) =
repl::ReadConcernArgs(clusterTime, rcIt.second);
@@ -2646,7 +2646,7 @@ TEST_F(TransactionRouterTestWithDefaultSession,
TEST_F(TransactionRouterTestWithDefaultSession, NonSnapshotReadConcernLevelsPreserveAfterOpTime) {
const auto opTime = repl::OpTime(Timestamp(10, 1), 2);
TxnNumber txnNum{3};
- for (auto rcIt : supportedNonSnapshotRCLevels) {
+ for (const auto& rcIt : supportedNonSnapshotRCLevels) {
repl::ReadConcernArgs::get(operationContext()) = repl::ReadConcernArgs(opTime, rcIt.second);
auto txnRouter = TransactionRouter::get(operationContext());
diff --git a/src/mongo/shell/shell_options.cpp b/src/mongo/shell/shell_options.cpp
index 69bbb071493..f22556d8347 100644
--- a/src/mongo/shell/shell_options.cpp
+++ b/src/mongo/shell/shell_options.cpp
@@ -311,7 +311,7 @@ Status storeMongoShellOptions(const moe::Environment& params,
if (params.count("setShellParameter")) {
auto ssp = params["setShellParameter"].as<std::map<std::string, std::string>>();
auto* paramSet = ServerParameterSet::getNodeParameterSet();
- for (auto it : ssp) {
+ for (const auto& it : ssp) {
const auto& name = it.first;
auto param = paramSet->getIfExists(name);
if (!param || !kSetShellParameterAllowlist.count(name)) {
diff --git a/src/mongo/unittest/unittest.cpp b/src/mongo/unittest/unittest.cpp
index cca577e3e87..a1f9dd9bfd7 100644
--- a/src/mongo/unittest/unittest.cpp
+++ b/src/mongo/unittest/unittest.cpp
@@ -501,7 +501,7 @@ int Suite::run(const std::vector<std::string>& suites,
std::vector<std::unique_ptr<Result>> results;
- for (std::string name : torun) {
+ for (const std::string& name : torun) {
std::shared_ptr<Suite>& s = suitesMap()[name];
fassert(16145, s != nullptr);
diff --git a/src/mongo/unittest/unittest_main.cpp b/src/mongo/unittest/unittest_main.cpp
index bb0c6692ba7..a5f747c68f7 100644
--- a/src/mongo/unittest/unittest_main.cpp
+++ b/src/mongo/unittest/unittest_main.cpp
@@ -123,7 +123,7 @@ int main(int argc, char** argv) {
if (list) {
auto suiteNames = ::mongo::unittest::getAllSuiteNames();
- for (auto name : suiteNames) {
+ for (const auto& name : suiteNames) {
std::cout << name << std::endl;
}
return static_cast<int>(mongo::ExitCode::clean);
diff --git a/src/mongo/util/concurrency/thread_pool_test_common.cpp b/src/mongo/util/concurrency/thread_pool_test_common.cpp
index 9ffe8f5a920..a1b4a415bf3 100644
--- a/src/mongo/util/concurrency/thread_pool_test_common.cpp
+++ b/src/mongo/util/concurrency/thread_pool_test_common.cpp
@@ -245,7 +245,7 @@ COMMON_THREAD_POOL_TEST(RepeatedScheduleDoesntSmashStack) {
void addTestsForThreadPool(const std::string& suiteName, ThreadPoolFactory makeThreadPool) {
auto& suite = unittest::Suite::getSuite(suiteName);
- for (auto testCase : threadPoolTestCaseRegistry()) {
+ for (const auto& testCase : threadPoolTestCaseRegistry()) {
suite.add(str::stream() << suiteName << "::" << testCase.first,
__FILE__,
[testCase, makeThreadPool] { testCase.second(makeThreadPool)->run(); });
diff --git a/src/mongo/util/pcre_test.cpp b/src/mongo/util/pcre_test.cpp
index d6d0c4c6b84..9e50aebbb74 100644
--- a/src/mongo/util/pcre_test.cpp
+++ b/src/mongo/util/pcre_test.cpp
@@ -69,7 +69,7 @@ TEST(PcreTest, BadPatterns) {
{"h)", Errc::ERROR_UNMATCHED_CLOSING_PARENTHESIS},
{"h\\", Errc::ERROR_END_BACKSLASH},
};
- for (auto [in, err] : badPatterns) {
+ for (const auto& [in, err] : badPatterns) {
Regex re{in};
ASSERT_FALSE(!!re);
ASSERT_EQ(re.error(), err);