2

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); 
ADV
  • 179
  • 9
  • What have you tried and where is the problem? Also are you sure that you want a *pointer* to this socket? There are other options for wrappers than smart pointers – UnholySheep Oct 14 '20 at 19:47
  • Possible duplicate of [smart pointer to manage socket file descriptor](https://stackoverflow.com/questions/29614775/) – Remy Lebeau Oct 14 '20 at 19:47

1 Answers1

4

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.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • Normally I would agree, the only reason I didn't in this example is because I've seen some compilers that fail on `using` in this context. But I think they are old compilers, obviously it should work fine in modern compilers. – Remy Lebeau Oct 14 '20 at 20:02