0

I am trying to create a simple thread using c++. I am getting the error: Error 14 error C2276: '&' : illegal operation on bound member function expression

This is my code:

void PeerCommunication(PeerData &peerData, std::string infoHash)
{
    Peer peer(peerData.GetIP(), peerData.GetPort(), infoHash);
    peer.CreateConnection();
    peer.HasPeace(0);
    peer.RecievePeace(0, 4056211 + 291); 
}

TcpPeers(OrderedMap<std::string, unsigned short> peers, std::string infoHash, Bencoding bencoder)
{
    std::vector<std::thread> threads;
    //std::thread ttt[num_threads];
    //std::thread t1(task1, "Hello");
    for (std::size_t i = 0; i < peers.GetSize(); i++)
    {
        PeerData pd(peers.GetKeyByIndex(i), peers.GetValueByIndex(i));
        std::thread t(&PeerCommunication, pd, infoHash);
        threads.push_back(t);
    }

    for (std::size_t i = 0; i < peers.GetSize(); i++)
    {
        threads.at(i).join();
    }
    ...
  }

I have tried to remove the reference: std::thread t(PeerCommunication, pd, infoHash); and it still doesn't works.

When I do it (remove the refernce) the error is: Error 4 error C3867: 'TcpPeers::PeerCommunication': function call missing argument list; use '&TcpPeers::PeerCommunication' to create a pointer to member

1 Answers1

0

You need to return something from your PeerCommunication() function.

I suspect you want something a little more like this:

for (std::size_t i = 0; i < peers.GetSize(); i++)
{
    PeerData pd(peers.GetKeyByIndex(i), peers.GetValueByIndex(i));

    // Use emplace as std::thread non-copyable
    // Pass this pointer with member functions
    // Use std::ref to pass references
    threads.emplace_back(&TcpPeers::PeerCommunication, this, std::ref(pd), infoHash);
}

for (std::size_t i = 0; i < peers.GetSize(); i++)
{
    threads.at(i).join();
}
Galik
  • 47,303
  • 4
  • 80
  • 117