- RAII does't execute destructor when call
exit.SoWSACleanupdoesn't run.What's the problem?I foundlibnetuseWSAStartupwithout anyWSACleanup, why? WSAStartupcan call many times in one process, so how can ensureWSACleanupenough?- How to use
WSAStartupandWSACleanupeasily and elegantly? - Additional I had wrote this test code for test
WSAStartupwithoutWSAClean, did not found any abnormal(growth of the memory or crash...)
code:
int main(int argc, char *argv[])
{
int res;
while (1) {
WSADATA wsadata;
res = WSAStartup(0x0202, &wsadata);
printf("WSAStartup 1 times:%d\n", res);
if (res != 0) {
printf("WSAStartup error:%d\n", WSAGetLastError());
exit(1);
}
res = WSAStartup(0x0202, &wsadata);
printf("WSAStartup 2 times:%d\n", res);
if (res != 0) {
printf("WSAStartup error:%d\n", WSAGetLastError());
exit(1);
}
}
return 0;
}
In my opinion,
exitwill destroy the object only when the object is allocated on stack, either static or global. It must not be allocated usingnew. In case ofnew, object must be explicitly deleted.Good practice is that
WSAStartupmust be called when application starts andWSACleanupwhen application ends. So, you can define a class which does this job in its constructor and destructor and define a global object of this class. This class will take care of this.You must have good reason to initialize WinSock multiple times. Otherwise, do only initialization once which you can do easily.