使用 C++ shared_ptr 用删除器包装 C 结构
Use C++ shared_ptr to wrap C struct with deleter
初学者的问题在这里:鉴于有一个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
总是具有值nullptr
,ptr
也将始终使用nullptr
初始化。对c_obj
的进一步更改对ptr
没有影响,地址已被复制。
解决方案是首先使用函数初始化c_obj
,然后使用它来初始化共享指针。只需在初始化ptr
之前放置func(&c_obj);
即可。
相关文章:
- std::vector的包装器,使数组的结构看起来像结构的数组
- C结构,其指针将被包装在unique_ptr中
- 将此私有删除器函数包装在结构中的目的是什么?
- C++-用和结构相同的语法围绕结构构造包装类
- 使用 C++ shared_ptr 用删除器包装 C 结构
- COM 自动化结构与它们的包装器
- 是可移植的包装结构
- OpenGL C++:VBO 的结构包装器不会初始化成员
- 将 c++ 函数包装为 c#,具有结构的总动态大小
- 带有柔性阵列构件的包装结构的便携式替代方案
- 叮当叮当当大约__attribute__((包装)),即使结构需要打包
- 有没有一种方法可以在基于枚举的可变参数模板函数之间进行选择,这比将函数包装在结构中更简单
- 带包装的尺寸结构(推,1)
- 包装结构的大小和带有不同编译器的继承
- C 的不同内存布局包装结构
- 使用cython包装c++结构模板
- 库,这有助于包装结构具有良好的性能
- 包装结构没有预期的大小
- Boost Asio 缓冲区中的包装结构
- 在 SWIG 中包装C++结构模板