使用 C++ shared_ptr 用删除器包装 C 结构

Use C++ shared_ptr to wrap C struct with deleter

本文关键字:包装 结构 删除 C++ shared ptr 使用      更新时间:2023-10-16

初学者的问题在这里:鉴于有一个C库在C中具有以下假定用法:

struct c_struct* c_obj = NULL;
func(&c_obj); //mallocs and fills c_struct
free_c_struct(c_obj); //my reponsibility to free it

用C++ shared_ptr包裹它的方法是什么? 尝试过这种方式 - 删除程序 (free_c_struct( 不起作用:

{
struct c_struct* c_obj = nullptr;
std::shared_ptr<struct c_struct> ptr (c_obj, free_c_struct);
//
// some amount of code
//
func(&c_obj);
//
// yet some amount of code, could return, or throw
// so I'm supposing "smart" functionality would do the work to free memory
//
//
//block ends, expect deleter to be called here
}

在块端,nullptr 传递给free_c_struct,但我想传递错误定位的地址。我完全错过了什么吗?

感谢您的关注。

更新:

一些可疑的方式:

void deleter(struct c_struct** o) {
free_c_struct(*o);
}
{
struct c_struct* c_obj = nullptr;
std::shared_ptr<struct c_struct*> c_obj_ptr (&c_obj, deleter);
//
// some amount of code
//
func(&c_obj);
}

这似乎做了我想做的,但看起来很奇怪,我应该写我自己的删除器(我宁愿不这样做(。

shared_ptr管理的指针与原始指针不同 - 它是它的副本。因此,您将创建一个管理 null 指针的std::shared_ptr对象。

稍后在同一指针的另一个副本上调用func时,将更改原始指针的值,但由std::shared_ptr管理的指针保持不变,并且仍为 null。

由于无法更改由shared_ptr管理的指针的值,解决此问题的唯一方法是在将指针传递给std::shared_ptr进行管理之前初始化指针。

std::shared_ptr<struct c_struct> ptr (c_obj, free_c_struct);创建一个指向c_obj指向对象的共享指针。由于此时c_obj总是具有值nullptrptr也将始终使用nullptr初始化。对c_obj的进一步更改对ptr没有影响,地址已被复制。

解决方案是首先使用函数初始化c_obj然后使用它来初始化共享指针。只需在初始化ptr之前放置func(&c_obj);即可。