David David - 2 months ago 29
C++ Question

What is the scope of a SOCKET object in Winsock?

The title pretty much says it all. I'm new to Winsock, and I need to know what the scope of a SOCKET object is.

Do I need to worry about it going out of scope when using it in a class member variable (since when it's returned, it's not dynamic memory)?


I'm pretty sure the answer to this is no, but since I can't find the info, I figured I would put it out there, for quick reference to others in the future.


The MSDN documentation for socket says the following:

When a session has been completed, a closesocket must be performed.

And the accompanying sample does just that. The documentation for closesocket is more forceful:

An application should always have a matching call to closesocket for each successful call to socket to return any socket resources to the system.

So as long as you keep the SOCKET descriptor somewhere you can use it until you call closesocket. You could consider putting it inside your own RAII type (or use an existing one) to avoid leaks. If you "forget" the descriptor, you will leak the internal resources.