Can i somehow pass socket from winsock2.h to unique_ptr and make custom deleter for him? Like this:
std::unique_ptr<SOCKET,deleter> up(new socket(...), deleter);
Can i somehow pass socket from winsock2.h to unique_ptr and make custom deleter for him? Like this:
std::unique_ptr<SOCKET,deleter> up(new socket(...), deleter);
Yes, it is possible, eg:
struct SocketDeleter
{
using pointer = SOCKET;
// or, if nenecessary:
// typedef SOCKET pointer;
void operator()(SOCKET sckt) const {
if (sckt != INVALID_SOCKET)
closesocket(sckt);
}
};
std::unique_ptr<SOCKET, SocketDeleter> up(socket(...));
However, SOCKET
is not a pointer type (it is a UINT
), and std::unique_ptr
is not really intended to be used with non-pointer types.
You could do something like this instead:
struct SocketDeleter
{
void operator()(SOCKET* sckt) const {
if (*sckt != INVALID_SOCKET)
closesocket(sckt);
delete sckt;
}
};
std::unique_ptr<SOCKET, SocketDeleter> up(new SOCKET(socket(...)), SocketDeleter{});
But that just gets ugly.
See smart pointer to manage socket file descriptor for alternative ways to design an RAII-style wrapper for a socket descriptor without using std::unique_ptr
.