Evgeniy175
Evgeniy175

Reputation: 334

C++ remove std::list element in loop issue

Good day. I want to understand, why this works good:

    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++;
        }   
    }

but this causes crash with message "abort() has been called":

    contacts.remove_if([](Contact c) {
        if (c.status != Contact::Status::disconnected)
            return false;

        c.handler.detach();

        return true;
    });

All this executes in separated thread inside critical section. List and critical section declared globally as:

CRITICAL_SECTION criticalSection;
std::list<Contact> contacts;

Upvotes: 0

Views: 73

Answers (2)

tinkertime
tinkertime

Reputation: 3042

You're effectively detaching a brand new Contact object due to your remove_if defintion taking by Value.

This is in contrast to the iterator version where you are detaching the actual Contact object inside of your contacts vector

Upvotes: 1

1201ProgramAlarm
1201ProgramAlarm

Reputation: 32717

In your lambda for remove_if, you're passing in a copy of the Contact, and detaching from that one. The original in the list does not get detached. Pass in a reference instead: remove_if([](Contact &c).

Upvotes: 4

Related Questions