Merge bitcoin/bitcoin#36682: refactor: Use std::erase and std::erase_if
What changed, and why it matters
This commit is a code cleanup that replaces older, more verbose ways of removing items from lists and vectors with newer C++20 standard helpers called std::erase and std::erase_if. It does not change what the program does, only how the source code expresses it. There is no security bug being fixed here.
No security action required. Treat as a normal code-quality refactor during review.
Security signals we found
No strong security signals were identified.
Evidence from the diff
The commit refactors container element removal across 13 files to use C++20 std::erase/std::erase_if instead of manual erase-remove idioms, std::list::remove/remove_if, or iterator-based erase loops. The PR description frames this as a readability/maintainability improvement and a way to avoid the bugprone-inaccurate-erase pattern, but the actual diff shows equivalent transformations with no functional change. No security vulnerability is addressed, and no incident or disclosure is referenced.
Changed components
src/common/args.cppsrc/httpserver.cppsrc/ipc/capnp/protocol.cppsrc/net.cppsrc/net_processing.cppsrc/node/eviction.cppsrc/node/mini_miner.cppsrc/rpc/server.cppsrc/test/fuzz/block_index_tree.cppsrc/test/fuzz/miniscript.cppsrc/test/fuzz/private_broadcast.cppsrc/txgraph.cppsrc/wallet/spend.cppInspect captured patch +34 / −69
### src/common/args.cpp
@@ -25,6 +25,7 @@
#include <algorithm>
#include <cstdlib>
#include <cstring>
+#include <list>
#include <map>
#include <optional>
#include <stdexcept>
@@ -162,7 +163,7 @@ std::list<SectionInfo> ArgsManager::GetUnrecognizedSections() const
LOCK(cs_args);
std::list<SectionInfo> unrecognized = m_config_sections;
- unrecognized.remove_if([](const SectionInfo& appeared){ return available_sections.contains(appeared.m_name); });
+ std::erase_if(unrecognized, [](const SectionInfo& appeared) { return available_sections.contains(appeared.m_name); });
return unrecognized;
}
### src/httpserver.cpp
@@ -290,10 +290,9 @@ void HTTPHeaders::Write(std::string&& key, std::string&& value)
void HTTPHeaders::RemoveAll(std::string_view key)
{
- auto moved = std::ranges::remove_if(m_headers, [key] (auto& pair) {
+ std::erase_if(m_headers, [key] (auto& pair) {
return CaseInsensitiveEqual(key, pair.first);
});
- m_headers.erase(moved.begin(), moved.end());
}
bool HTTPHeaders::Read(util::LineReader& reader, bool write)
### src/ipc/capnp/protocol.cpp
@@ -19,6 +19,7 @@
#include <cassert>
#include <cerrno>
#include <future>
+#include <list>
#include <memory>
#include <mutex>
#include <optional>
@@ -112,7 +113,7 @@ class CapnpProtocol : public Protocol
// process (if there is one), since a parent process should be able to
// monitor and control this process, even during shutdown.
m_loop->sync([&] {
- m_loop->m_incoming_connections.remove_if([this](mp::Connection& c) { return &c != m_parent_connection; });
+ std::erase_if(m_loop->m_incoming_connections, [this](mp::Connection& c) { return &c != m_parent_connection; });
});
}
mp::Stream makeStream(mp::SocketId socket) override
### src/net.cpp
@@ -44,9 +44,11 @@
#include <cstdint>
#include <cstring>
#include <functional>
+#include <list>
#include <optional>
#include <string_view>
#include <unordered_map>
+#include <vector>
TRACEPOINT_SEMAPHORE(net, closed_connection);
TRACEPOINT_SEMAPHORE(net, evicted_inbound_connection);
@@ -1972,7 +1974,7 @@ void CConnman::DisconnectNodes()
if (pnode->fDisconnect)
{
// remove from m_nodes
- m_nodes.erase(remove(m_nodes.begin(), m_nodes.end(), pnode), m_nodes.end());
+ std::erase(m_nodes, pnode);
// Add to reconnection list if appropriate. We don't reconnect right here, because
// the creation of a connection is a blocking operation (up to several seconds),
@@ -2010,7 +2012,7 @@ void CConnman::DisconnectNodes()
{
// Destroy the object only after other threads have stopped using it.
if (pnode->GetRefCount() <= 0) {
- m_nodes_disconnected.remove(pnode);
+ std::erase(m_nodes_disconnected, pnode);
DeleteNode(pnode);
}
}
@@ -2720,9 +2722,7 @@ void CConnman::ThreadOpenConnections(const std::vector<std::string> connect, std
// In case previously unreachable networks become reachable
// (e.g. in case of -onlynet changes by the user), fixed seeds will
// be loaded only for networks for which we have no addresses.
- seed_addrs.erase(std::remove_if(seed_addrs.begin(), seed_addrs.end(),
- [&fixed_seed_networks](const CAddress& addr) { return !fixed_seed_networks.contains(addr.GetNetwork()); }),
- seed_addrs.end());
+ std::erase_if(seed_addrs, [&fixed_seed_networks](const CAddress& addr) { return !fixed_seed_networks.contains(addr.GetNetwork()); });
CNetAddr local;
local.SetInternal("fixedseeds");
addrman.get().Add(seed_addrs, local);
@@ -3839,9 +3839,7 @@ std::vector<CAddress> CConnman::GetAddressesUnsafe(size_t max_addresses, size_t
{
std::vector<CAddress> addresses = addrman.get().GetAddr(max_addresses, max_pct, network, filtered);
if (m_banman) {
- addresses.erase(std::remove_if(addresses.begin(), addresses.end(),
- [this](const CAddress& addr){return m_banman->IsDiscouraged(addr) || m_banman->IsBanned(addr);}),
- addresses.end());
+ std::erase_if(addresses, [this](const CAddress& addr) { return m_banman->IsDiscouraged(addr) || m_banman->IsBanned(addr); });
}
return addresses;
}
### src/net_processing.cpp
@@ -88,6 +88,7 @@
#include <typeinfo>
#include <unordered_set>
#include <utility>
+#include <vector>
using kernel::ChainstateRole;
using namespace util::hex_literals;
@@ -5795,8 +5796,7 @@ void PeerManagerImpl::MaybeSendAddr(CNode& node, Peer& peer, std::chrono::micros
if (!ret) peer.m_addr_known->insert(addr.GetKey());
return ret;
};
- peer.m_addrs_to_send.erase(std::remove_if(peer.m_addrs_to_send.begin(), peer.m_addrs_to_send.end(), addr_already_known),
- peer.m_addrs_to_send.end());
+ std::erase_if(peer.m_addrs_to_send, addr_already_known);
// No addr messages to send
if (peer.m_addrs_to_send.empty()) return;
### src/node/eviction.cpp
@@ -86,20 +86,12 @@ static void EraseLastKElements(
void ProtectNoBanConnections(std::vector<NodeEvictionCandidate>& eviction_candidates)
{
- eviction_candidates.erase(std::remove_if(eviction_candidates.begin(), eviction_candidates.end(),
- [](NodeEvictionCandidate const& n) {
- return n.m_noban;
- }),
- eviction_candidates.end());
+ std::erase_if(eviction_candidates, [](const NodeEvictionCandidate& n) { return n.m_noban; });
}
void ProtectOutboundConnections(std::vector<NodeEvictionCandidate>& eviction_candidates)
{
- eviction_candidates.erase(std::remove_if(eviction_candidates.begin(), eviction_candidates.end(),
- [](NodeEvictionCandidate const& n) {
- return n.m_conn_type != ConnectionType::INBOUND;
- }),
- eviction_candidates.end());
+ std::erase_if(eviction_candidates, [](const NodeEvictionCandidate& n) { return n.m_conn_type != ConnectionType::INBOUND; });
}
void ProtectEvictionCandidatesByRatio(std::vector<NodeEvictionCandidate>& eviction_candidates)
@@ -210,8 +202,7 @@ void ProtectEvictionCandidatesByRatio(std::vector<NodeEvictionCandidate>& evicti
// This happens after the other preferences since if a peer is really the best by other criteria (esp relaying blocks)
// then we probably don't want to evict it no matter what.
if (std::any_of(vEvictionCandidates.begin(),vEvictionCandidates.end(),[](NodeEvictionCandidate const &n){return n.prefer_evict;})) {
- vEvictionCandidates.erase(std::remove_if(vEvictionCandidates.begin(),vEvictionCandidates.end(),
- [](NodeEvictionCandidate const &n){return !n.prefer_evict;}),vEvictionCandidates.end());
+ std::erase_if(vEvictionCandidates, [](const NodeEvictionCandidate& n) { return !n.prefer_evict; });
}
// Identify the network group with the most connections and youngest member.
### src/node/mini_miner.cpp
@@ -18,6 +18,7 @@
#include <numeric>
#include <ranges>
#include <utility>
+#include <vector>
namespace node {
@@ -221,9 +222,7 @@ void MiniMiner::DeleteAncestorPackage(const std::set<MockEntryMap::iterator, Ite
// respective descendants exactly once.
Assume(anc->second.GetModFeesWithAncestors() == 0);
Assume(anc->second.GetSizeWithAncestors() == 0);
- auto vec_it = std::find(m_entries.begin(), m_entries.end(), anc);
- Assume(vec_it != m_entries.end());
- m_entries.erase(vec_it);
+ Assume(std::erase(m_entries, anc) == 1);
m_entries_by_txid.erase(anc);
}
}
### src/rpc/server.cpp
@@ -36,6 +36,7 @@
#include <unordered_map>
#include <unordered_set>
#include <variant>
+#include <vector>
using util::SplitString;
@@ -635,9 +636,7 @@ bool CRPCTable::removeCommand(const std::string& name, const CRPCCommand* pcmd)
{
auto it = mapCommands.find(name);
if (it != mapCommands.end()) {
- auto new_end = std::remove(it->second.begin(), it->second.end(), pcmd);
- if (it->second.end() != new_end) {
- it->second.erase(new_end, it->second.end());
+ if (std::erase(it->second, pcmd)) {
if (it->second.empty()) {
mapCommands.erase(it);
}
### src/test/fuzz/block_index_tree.cpp
@@ -17,6 +17,7 @@
#include <validation.h>
#include <ranges>
+#include <unordered_map>
#include <vector>
const TestingSetup* g_setup;
@@ -213,13 +214,7 @@ FUZZ_TARGET(block_index_tree, .init = initialize_block_index_tree)
blockman.CleanupForFuzzing();
// Delete all blocks but Genesis from block index
uint256 genesis_hash = genesis->GetBlockHash();
- for (auto it = blockman.m_block_index.begin(); it != blockman.m_block_index.end();) {
- if (it->first != genesis_hash) {
- it = blockman.m_block_index.erase(it);
- } else {
- ++it;
- }
- }
+ std::erase_if(blockman.m_block_index, [&](const auto& entry) { return entry.first != genesis_hash; });
chainman.ActiveChainstate().TryAddBlockIndexCandidate(genesis);
assert(blockman.m_block_index.size() == 1);
assert(chainman.ActiveChainstate().setBlockIndexCandidates.size() == 1);
### src/test/fuzz/miniscript.cpp
@@ -15,7 +15,9 @@
#include <util/strencodings.h>
#include <algorithm>
+#include <map>
#include <optional>
+#include <vector>
namespace {
@@ -695,13 +697,7 @@ struct SmartInfo
if (useful_types.size() == set_size) break;
}
// Remove all rules that construct uninteresting types.
- for (auto type_it = table.begin(); type_it != table.end();) {
- if (!useful_types.contains(type_it->first)) {
- type_it = table.erase(type_it);
- } else {
- ++type_it;
- }
- }
+ std::erase_if(table, [&](const auto& entry) { return !useful_types.contains(entry.first); });
/* Find which types are constructible. A type is constructible if there is a leaf
* node recipe for constructing it, or a recipe whose subnodes are all constructible.
@@ -731,10 +727,9 @@ struct SmartInfo
}
for (auto type_it = table.begin(); type_it != table.end();) {
// Remove all recipes which involve non-constructible types.
- type_it->second.erase(std::remove_if(type_it->second.begin(), type_it->second.end(),
- [&](const recipe& rec) {
- return !std::all_of(rec.second.begin(), rec.second.end(), known_constructible);
- }), type_it->second.end());
+ std::erase_if(type_it->second, [&](const recipe& rec) {
+ return !std::all_of(rec.second.begin(), rec.second.end(), known_constructible);
+ });
// Delete types entirely which have no recipes left.
if (type_it->second.empty()) {
type_it = table.erase(type_it);
### src/test/fuzz/private_broadcast.cpp
@@ -104,13 +104,7 @@ FUZZ_TARGET(private_broadcast)
tx_it->second = 0;
planned_sends[tx] = PrivateBroadcast::INITIAL_CONNECTION_COUNT;
resolved_transactions.erase(tx);
- for (auto it = nodes_sent_to.begin(); it != nodes_sent_to.end();) {
- if (CTransactionRefComp{}(it->second, tx)) {
- it = nodes_sent_to.erase(it);
- } else {
- ++it;
- }
- }
+ std::erase_if(nodes_sent_to, [&](const auto& entry) { return CTransactionRefComp{}(entry.second, tx); });
}
} else if (transactions.size() >= cap) {
Assert(res == PrivateBroadcast::AddResult::QueueFull);
@@ -128,13 +122,7 @@ FUZZ_TARGET(private_broadcast)
const CTransactionRef& tx{transactions_it->first};
// Remove relevant entries from nodes_sent_to[] if any.
- for (auto it = nodes_sent_to.begin(); it != nodes_sent_to.end();) {
- if (CTransactionRefComp{}(it->second, tx)) {
- it = nodes_sent_to.erase(it);
- } else {
- ++it;
- }
- }
+ std::erase_if(nodes_sent_to, [&](const auto& entry) { return CTransactionRefComp{}(entry.second, tx); });
const auto remaining_sends{pb.Remove(tx)};
### src/txgraph.cpp
@@ -19,6 +19,7 @@
#include <span>
#include <unordered_set>
#include <utility>
+#include <vector>
namespace {
@@ -1288,9 +1289,7 @@ void GenericClusterImpl::ApplyRemovals(TxGraphImpl& graph, int level, std::span<
m_mapping.resize(m_depgraph.PositionRange());
// Filter removed transactions out of m_linearization.
- m_linearization.erase(std::remove_if(m_linearization.begin(), m_linearization.end(),
- [&](auto pos) { return todo[pos]; }),
- m_linearization.end());
+ std::erase_if(m_linearization, [&](auto pos) { return todo[pos]; });
Compact();
graph.GetClusterSet(level).m_cluster_usage += TotalMemoryUsage();
### src/wallet/spend.cpp
@@ -31,6 +31,7 @@
#include <wallet/wallet.h>
#include <cmath>
+#include <vector>
using common::StringForFeeReason;
using common::TransactionErrorString;
@@ -213,7 +214,7 @@ std::vector<COutput> CoinsResult::All() const
void CoinsResult::Erase(const std::unordered_set<COutPoint, SaltedOutpointHasher>& coins_to_remove)
{
for (auto& [type, vec] : coins) {
- auto remove_it = std::remove_if(vec.begin(), vec.end(), [&](const COutput& coin) {
+ std::erase_if(vec, [&](const COutput& coin) {
// remove it if it's on the set
if (!coins_to_remove.contains(coin.outpoint)) return false;
@@ -222,7 +223,6 @@ void CoinsResult::Erase(const std::unordered_set<COutPoint, SaltedOutpointHasher
if (coin.HasEffectiveValue() && total_effective_amount.has_value()) total_effective_amount = *total_effective_amount - coin.GetEffectiveValue();
return true;
});
- vec.erase(remove_it, vec.end());
}
}
Why this scored 15/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.