Smart pointers with addrinfo struct

I need to deal with two struct pointers addrinfo. Since I am coding in C ++ (11), I have to make the code safe for the code. In fact, my business structures may throw it away runtime_error. If you no longer need such a structure, you must call freeaddrinfoto free the list inside the structure. Please consider the following code:

#include <memory>
#include <netdb.h>

class SomeOtherClass
{
  public:
    SomeOtherClass() : hints(new addrinfo), result(new addrinfo) { /*stuff*/ }
    ~SomeOtherClass() { freeaddrinfo(result.get()); } // bad things will happen

private:
    std::unique_ptr<addrinfo> hints, result;
};

class MyClass : public SomeOtherClass
{
public:
    MyClass() { /* hints initialization, call to getaddrinfo, etc. */ }

private:
    // ...
};

My questions:

  • addrinfo is the "old" C structure, without calling ctor / dtor: is it safe to use the new ones?
  • getaddrinfoa pointer to a pointer to a structure is required addrinfo: how to pass it using smart pointers?
  • How about a call freeaddrinfo? It was considered unsafe to remove (or better free) the pointer that holds the smart pointer.

hints , .

+3
1

addrinfo , new delete, unique_ptr .

addrinfo addrinfo getaddrinfo(), freeaddrinfo() . unique_ptr , freeaddrinfo() Deleter, :

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;
};

:

getaddrinfo(..., &result);

, std::unique_ptr &:

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

: - decltype Deleter:

std::unique_ptr<addrinfo, decltype(&freeaddrinfo)> result;
+6

All Articles