refactor: Rewrite InsertBlockIndex with try_emplace

Credit to ajtowns for this suggestion, thanks!
This commit is contained in:
Carl Dong 2022-01-13 12:37:06 -05:00
parent 531dce0347
commit dd79dad175

View file

@ -208,19 +208,13 @@ CBlockIndex* BlockManager::InsertBlockIndex(const uint256& hash)
return nullptr; return nullptr;
} }
// Return existing // Return existing or create new
BlockMap::iterator mi = m_block_index.find(hash); auto [mi, inserted] = m_block_index.try_emplace(hash);
if (mi != m_block_index.end()) { CBlockIndex* pindex = &(*mi).second;
return &(*mi).second; if (inserted) {
pindex->phashBlock = &((*mi).first);
} }
return pindex;
// Create new
CBlockIndex new_index{};
mi = m_block_index.insert(std::make_pair(hash, std::move(new_index))).first;
CBlockIndex* pindexNew = &(*mi).second;
pindexNew->phashBlock = &((*mi).first);
return pindexNew;
} }
bool BlockManager::LoadBlockIndex( bool BlockManager::LoadBlockIndex(