std :: unique_ptr用于需要免费的C函数 [英] std::unique_ptr for C functions that need free
问题描述
想一个返回必须 free
d的C函数,例如POSIX的 strdup()
。我想在C ++ 11中使用该函数,并避免任何泄漏的机会,这是正确的方法吗?
Think to a C function that return something that must be free
d, for example the POSIX's strdup()
. I want to use that function in C++11 and avoid any chance of leaks, is this a correct way?
#include <memory>
#include <iostream>
#include <string.h>
int main() {
char const* t { "Hi stackoverflow!" };
std::unique_ptr<char, void(*)(void*)>
t_copy { strdup(t), std::free };
std::cout << t_copy.get() << " <- this is the copy!" <<std::endl;
}
假设有意义,指针?例如对于POSIX的函数 open
,返回 int
?
Assuming it makes sense, it is possible to use a similar pattern with non-pointers? For example for the POSIX's function open
that returns an int
?
推荐答案
你有什么很可能在实践中工作,但不是严格正确。但是,正确的版本可以更可读:
What you have is extremely likely to work in practice, but not strictly correct. However, the correct version is arguably even more readable:
std::unique_ptr<char, decltype(std::free) *>
t_copy { strdup(t), std::free };
原因是函数类型 std :: free
不能保证 void(void *)
。它保证取一个 void *
,并返回 void
,但有两个函数类型匹配该规范:一个具有C键,一个具有C ++键。大多数编译器不会注意到,但为了正确,你应该避免对它做出假设。
The reason is that the function type of std::free
is not guaranteed to be void(void*)
. It is guaranteed to take a void*
, and to return void
, but there are two function types that match that specification: one with C linkage, and one with C++ linkage. Most compilers pay no attention to that, but for correctness, you should avoid making assumptions about it.
假设有意义,要使用非指针类似的模式?
Assuming it makes sense, it is possible to use a similar pattern with non-pointers?
不能使用 unique_ptr
这是真正特定于指针。但是你可以创建自己的类,类似于 unique_ptr
,但没有对被包裹对象做出假设。
Not with unique_ptr
, which is really specific to pointers. But you could create your own class, similar to unique_ptr
, but without making assumptions about the object being wrapped.
这篇关于std :: unique_ptr用于需要免费的C函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!