I have the following code :
try
{
HAS::TCPServerSocket servSock(echoServPort); // Socket descriptor for server
std::vector<HAS::TCPSocket*> sockets(MAXCONN);
for (;;)
{
try
{
if (socketCount < MAXCONN)
{
HAS::TCPSocket* sock(servSock.accept());
sockets.push_back(sock);
std::thread handler(handleTCPClient, std::ref(sockets[socketCount++]));
handler.detach();
}
}
catch (...)
{
cerr << "Unable to create thread" << endl;
exit(1);
}
}
}
I want to keep track of a limited number of connections (MAXCONN=4) and would like to keep track of opened sockets using a std::vector. Somehow, when I use the above code the sock variable gets properly set to the current socket as accepted by servSock.accept(). However, when I try to push the sock variable onto the std::vector I loose the sock object.
I have a feeling it has to do with properly specifying a copy and/or move constructor but I have defined both (and used breakpoints to see when the would be called) but they don’t seem to get called at all.
References to vector elements are invalidated when you say
push_back. You can’t use the code the way you have. You must first populate the entire vector and then never touch it again. Alternatively, use a container whose element references aren’t invalidated by container mutations (listormultisetorunordered_multisetfor general purpose,dequefor insertion/deletion at the ends).Or just pass a copy of the pointer to the thread?!