简介
asio中,winsock初始化工作是放在winsock_init类中来处理的
类结构
winsock_init_base:提供了静态方法startup和cleanup,其中startup主要是调用WSAStartup,内部保证只调用一次,cleanup是调用WSACleanup,只有在data的init_count_为0时,才会调用WSACleanup
void winsock_init_base::startup(data& d,unsigned char major, unsigned char minor)
{if (::InterlockedIncrement(&d.init_count_) == 1){WSADATA wsa_data;long result = ::WSAStartup(MAKEWORD(major, minor), &wsa_data);::InterlockedExchange(&d.result_, result);}
}void winsock_init_base::cleanup(data& d)
{if (::InterlockedDecrement(&d.init_count_) == 0){::WSACleanup();}
}
winsock_init:是模板类,其有两个非类型模板参数,表示winsock库的major,minor版本,其私有继承winsock_init_base
template <int Major = 2, int Minor = 0>
class winsock_init : private winsock_init_base
{
public:winsock_init(bool allow_throw = true){startup(data_, Major, Minor);if (allow_throw)throw_on_error(data_);}winsock_init(const winsock_init&){startup(data_, Major, Minor);throw_on_error(data_);}~winsock_init(){cleanup(data_);}
};