Search code examples
c++network-programmingsfml

Binary '==': no operator found - TCP Socket SFML


I'm trying to loop through a std::list<sf::TcpSocket> clients and delete the disconnected ones from sf::SocketSelector and from the list itself. When trying to delete the client from the list, using an iterator, I keep getting a "binary '==' no operator found" error. This is the part of the code where the error is triggered from:

std::list<sf::TcpSocket> clients;
std::list<sf::TcpSocket>::iterator i;

for (auto i = clients.begin(); i != clients.end();)
{
    if (selector.isReady(*i))
    {
        sf::Socket::Status status = i->receive(dummy, 1, received);
        if (status != sf::Socket::Done)
        {
            if (status == sf::Socket::Disconnected)
            {
                selector.remove(*i);
                clients.remove(*i);  // this causes the error
            }
        }
        else
        {
            //i++;
        }
    }
}

Solution

  • Remove the object with its iterator, you already have it:

    std::list<sf::TcpSocket> clients;
    std::list<sf::TcpSocket>::iterator i;
    
    for (auto i = clients.begin(); i != clients.end();)
    {
        if (selector.isReady(*i))
        {
            sf::Socket::Status status = i->receive(dummy, 1, received);
            if (status != sf::Socket::Done)
            {
                if (status == sf::Socket::Disconnected)
                {
                    selector.remove(*i);
                    i = clients.erase(i); // Properly update the iterator
                }
            }
            else
            {
                ++i;
            }
        }
    }