具有addrinfo结构的智能指针 [英] Smart pointers with addrinfo struct

查看:81
本文介绍了具有addrinfo结构的智能指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要处理两个结构 addrinfo 指针。由于我使用C ++(11)进行编码,因此必须使我的代码具有异常安全性。确实,我的构造函数可能会抛出 runtime_error
当您不再需要这种结构时,应调用 freeaddrinfo 以便释放结构中的列表。请考虑以下代码:

I need to deal with two struct addrinfo pointers. Since I'm coding in C++(11), I've to make my code exception-safe. Indeed, my costructors may throw a runtime_error. When you don't need that kind of struct anymore, you should call freeaddrinfo in order to free the list inside the struct. 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:
    // ...
};

我的问题是:


  1. addrinfo 是旧的 C结构,没有ctor / dtor可以调用:使用新的安全吗?

  2. getaddrinfo 需要一个指向 addrinfo 结构的指针的指针:如何通过智能指针传递它?

  3. 调用 freeaddrinfo 怎么样?删除(或更好的 free )智能指针持有的指针被认为是不安全的。

  1. addrinfo is an "old" C structure, with no ctor/dtor to call: is it safe to use new?
  2. getaddrinfo requires a pointer to a pointer to a addrinfo struct: how should I pass it via smart pointers?
  3. What about calling freeaddrinfo? It's considered unsafe to delete (or better free) the pointer that the smart pointer is holding.

对于提示来说没有问题,因为其生存期更短。

For hints there is no problem, since its lifetime is smaller.

推荐答案

对于您分配的任何 addrinfo ,使用都是安全的删除,因此您可以使用 unique_ptr

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.

对于任何 getaddrinfo() addrinfo c $ c>分配,您必须使用 freeaddrinfo()释放它。您仍然可以使用 unique_ptr ,但是必须指定 freeaddrinfo()作为自定义删除器,例如:

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

或者,如果 std :: unique_ptr 不会覆盖& 运算符:

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

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

更新:更好的选择是使用 decltype 并让编译器为您推断 Deleter 的函数类型:

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;

这篇关于具有addrinfo结构的智能指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆