unique_ptr 和带有 C API 的库,带有指向指针函数参数的指针

Gri*_*ory 1 c++ pointers smart-pointers

假设我有一个库,它初始化一个对象,如下所示:

Type *object;

lib_init(&object); // lib_init takes Type **object as the parameter
Run Code Online (Sandbox Code Playgroud)

那么,如果我想在使用智能指针的代码中使用该库该怎么办?这是正确的方法吗?

Type *pObject;
lib_init(&pObject);
unique_ptr<Type> object(nullptr);
object.reset(pObject);
Run Code Online (Sandbox Code Playgroud)

或者有一个聪明的方法来做到这一点?

jua*_*nza 5

您可以将初始化包装到返回唯一指针的函数中:

std::unique_ptr<Type> init_type()
{
  Type* p;
  lib_init(&p);
  return std::unique_ptr<Type>(p);
}
Run Code Online (Sandbox Code Playgroud)

然后

 std::unique_ptr<Type> object(init_type());
Run Code Online (Sandbox Code Playgroud)

请记住,除非要使用 取消分配指针delete,否则您还需要提供自定义删除器。例如,假设解除分配函数为void lib_dispose(Type*),则

std::unique_ptr<Type, void (*)(Type*)> init_type()
{
  Type* p;
  lib_init(&p);
  return std::unique_ptr<Type, void (*)(Type*)>(p, lib_dispose);
}
Run Code Online (Sandbox Code Playgroud)