Smart pointers with addrinfo struct

北战南征 提交于 2019-12-06 01:57:05

For any addrinfo you allocate yourself, it is safe to use newand delete, so you can use the default implementation of unique_ptr to handle that.

For any addrinfo that getaddrinfo() allocates, you must use freeaddrinfo() to free it. You can still use unique_ptr for that, but you must specify freeaddrinfo() as a custom Deleter, eg:

class SomeOtherClass
{
  public:
    SomeOtherClass() : hints(new addrinfo), result(nullptr, &freeaddrinfo) { /*stuff*/ }

private:
    std::unique_ptr<addrinfo> hints;
    std::unique_ptr<addrinfo, void(__stdcall*)(addrinfo*)> result;
};

Then you can do this:

getaddrinfo(..., &result);

Or this, if std::unique_ptr does not override the & operator:

addrinfo *temp;
getaddrinfo(..., &temp);
result.reset(temp);

UPDATE: a better option is to use decltype and let the compiler deduce the function type of the Deleter for you:

std::unique_ptr<addrinfo, decltype(&freeaddrinfo)> result;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!