oh i'm not familiar implementing ref counting. this is the code i was talking about
mySocket.h
Code:
#if !defined(_MYSOCKET_H)
#define _MYSOCKET_H
#include <string>
#include <winsock2.h>
#pragma comment (lib, "ws2_32.lib") // avoids manually specifying this lib file to the linker
class mySocket
{
private:
SOCKET _hSocket; // winsock handle
public:
mySocket( const std::string& protocol )
{
// winsock data
static const int winsock_ver_minimum = 2;
WSADATA wsaData;
// start winsock
WSAStartup( MAKEWORD(winsock_ver_minimum,0), &wsaData);
// acquire socket handle
_hSocket = INVALID_SOCKET;
if( protocol == "TCP" )
{
_hSocket = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP );
}
else if( protocol == "UDP" )
{
_hSocket = socket( AF_INET, SOCK_DGRAM, IPPROTO_UDP );
}
}
mySocket& operator=( mySocket& other )
{
// destroy old socket handle
if( _hSocket != INVALID_SOCKET )
{
closesocket( _hSocket );
}
_hSocket = other._hSocket; // copy other socket handle
other._hSocket = INVALID_SOCKET; // prevent other from destroying socket handle
return *this; // return this
}
// destroy socket
~mySocket()
{
if( _hSocket != INVALID_SOCKET )
{
closesocket( _hSocket );
}
}
};
#endif //_MYSOCKET_H
main.cpp
Code:
#include "mySocket.h"
int main( int argc, char* argv[] )
{
mySocket objSocket( "TCP" );
objSocket = mySocket( "TCP" );
mySocket objSocket2( "TCP" );
objSocket = objSocket2; // objSocket2::_hSocket will contain INVALID_SOCKET
return 0;
}
any suggestions are welcome.