I have a Client class which throws a compile error:
class Client {
public:
struct sockaddr_in* sa;
int roomid;
Client(struct sockaddr_in* socka, int id=0) : sa(socka), roomid(id) {}
};
Error:
chatserver.cc:37:2: note: candidate expects 2 arguments, 0 provided
chatserver.cc:33:7: note: candidate: ‘constexpr Client::Client(const Client&)’
33 | class Client {
| ^~~~~~
However, if I add an empty constructor, Client() {}
, then it compiles fine.
Why?
EDIT:
I've condensed the code so it's more readable.
Basically, I initialise an unordered_map, then at the beginning of a while loop, I loop through the map to print its contents. Further downstream the loop, I listen on a UDP socket and add a new Client to the map:
unordered_map<string, Client> ip_client_map;
while (true) {
for (auto const& x : ip_client_map) {
cout << x.first << '=' << x.second.sa->sin_addr.s_addr << ':' << ntohs(x.second.sa->sin_port) << endl;
}
struct sockaddr_in src;
socklen_t srclen = sizeof(src);
char buf[1000];
int rlen = recvfrom(sockfd, buf, sizeof(buf)-1, 0, (struct sockaddr*) &src, &srclen);
buf[rlen] = 0;
string srcaddr = string(inet_ntoa(src.sin_addr)) + ":" + to_string(ntohs(src.sin_port));
struct sockaddr_in* sa = (sockaddr_in*) malloc(sizeof(struct sockaddr_in));
memcpy(sa, &src, sizeof(struct sockaddr_in));
Client new_client = Client(sa);
ip_client_map[srcaddr] = new_client;
}
Sidenote: each time I print the contents of the unordered_map at the beginning of the while loop, the IP address and port number are 0 and 0, so I think I'm not copying the sockaddr_in*
properly.