Skip to content

Commit 45cf5ce

Browse files
committed
ProgramMemory: avoid unnecessary copy in erase_if() [skip ci]
1 parent f4c9f3a commit 45cf5ce

1 file changed

Lines changed: 25 additions & 3 deletions

File tree

lib/programmemory.cpp

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -173,10 +173,32 @@ void ProgramMemory::erase_if(const std::function<bool(const ExprIdToken&)>& pred
173173
if (mValues->empty())
174174
return;
175175

176-
// TODO: how to delay until we actuallly modify?
177-
copyOnWrite();
176+
auto it = std::find_if(mValues->cbegin(), mValues->cend(), [&pred](const std::pair<const ExprIdToken, ValueFlow::Value>& entry) {
177+
return pred(entry.first);
178+
});
179+
if (it == mValues->cend())
180+
return;
181+
182+
if (mValues.use_count() == 1)
183+
{
184+
it = mValues->erase(it);
185+
}
186+
else
187+
{
188+
const auto& exprIdTok = it->first;
189+
190+
copyOnWrite();
191+
192+
it = mValues->cbegin();
193+
for (; it != mValues->cend(); ++it) {
194+
if (it->first == exprIdTok) {
195+
it = mValues->erase(it);
196+
break;
197+
}
198+
}
199+
}
178200

179-
for (auto it = mValues->begin(); it != mValues->end();) {
201+
for (; it != mValues->cend();) {
180202
if (pred(it->first))
181203
it = mValues->erase(it);
182204
else

0 commit comments

Comments
 (0)