具有addrinfo结构的智能指针 [英] Smart pointers with addrinfo struct
问题描述
我需要处理两个结构 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:
// ...
};
我的问题是:
-
addrinfo
是旧的 C结构,没有ctor / dtor可以调用:使用新的安全吗? -
getaddrinfo
需要一个指向addrinfo
结构的指针的指针:如何通过智能指针传递它? - 调用
freeaddrinfo
怎么样?删除(或更好的free
)智能指针持有的指针被认为是不安全的。
addrinfo
is an "old" C structure, with no ctor/dtor to call: is it safe to use new?getaddrinfo
requires a pointer to a pointer to aaddrinfo
struct: how should I pass it via smart pointers?- What about calling
freeaddrinfo
? It's considered unsafe to delete (or betterfree
) the pointer that the smart pointer is holding.
对于提示
来说没有问题,因为其生存期更短。
For hints
there is no problem, since its lifetime is smaller.
推荐答案
对于您分配的任何 addrinfo
,使用都是安全的新
和删除
,因此您可以使用 unique_ptr $ c $的默认实现
For any addrinfo
you allocate yourself, it is safe to use new
and 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屋!