C++ 删除循环问题中的 std::list 元素
C++ remove std::list element in loop issue
美好的一天。我想了解,为什么这很好用:
std::list<Contact>::iterator it = contacts.begin();
while (it != contacts.end()) {
if ((*it).status == Contact::Status::disconnected) {
(*it).handler.detach();
it = contacts.erase(it);
}
else {
it++;
}
}
但这会导致崩溃并显示消息 "abort() has been called":
contacts.remove_if([](Contact c) {
if (c.status != Contact::Status::disconnected)
return false;
c.handler.detach();
return true;
});
所有这些都在临界区内的单独线程中执行。全局声明的列表和临界区为:
CRITICAL_SECTION criticalSection;
std::list<Contact> contacts;
在 remove_if
的 lambda 中,您正在传递联系人的 副本,并从该联系人中分离。列表中的原始文件不会分离。改为传入参考:remove_if([](Contact &c)
.
由于您的 remove_if
定义采用了 Value,因此您实际上 detach
正在创建一个全新的 Contact
对象。
这与您在detach
contacts
向量
中 detach
实际的 Contact 对象的迭代器版本形成对比
美好的一天。我想了解,为什么这很好用:
std::list<Contact>::iterator it = contacts.begin();
while (it != contacts.end()) {
if ((*it).status == Contact::Status::disconnected) {
(*it).handler.detach();
it = contacts.erase(it);
}
else {
it++;
}
}
但这会导致崩溃并显示消息 "abort() has been called":
contacts.remove_if([](Contact c) {
if (c.status != Contact::Status::disconnected)
return false;
c.handler.detach();
return true;
});
所有这些都在临界区内的单独线程中执行。全局声明的列表和临界区为:
CRITICAL_SECTION criticalSection;
std::list<Contact> contacts;
在 remove_if
的 lambda 中,您正在传递联系人的 副本,并从该联系人中分离。列表中的原始文件不会分离。改为传入参考:remove_if([](Contact &c)
.
由于您的 remove_if
定义采用了 Value,因此您实际上 detach
正在创建一个全新的 Contact
对象。
这与您在detach
contacts
向量
detach
实际的 Contact 对象的迭代器版本形成对比