用typedef结构体增强shared_ptr
Boost shared_ptr with typedef struct
我有libmodbus的编译问题。我有以下代码
boost::shared_ptr <modbus_t> ctx;
ctx->modbus_new_tcp(ip_address.c_str(), modbus_port);
但是我得到以下错误
error: invalid use of incomplete type 'struct _modbus'
它指向modbus.h
中的这一行typedef struct _modbus modbus_t;
我对这个了解不够,无法解决我的问题。你觉得是什么?这个库与智能指针不兼容吗?他们告诉你使用常规指针
modbus_t* ctx;
谢谢。
你可以——也许——使用
if (std::unique_ptr<modbus_t, void(*)(modbus_t*)> mb(modbus_new_tcp(ip_address.c_str(), modbus_port), &modbus_free)) {
modbus_connect(mb);
/* Read 5 registers from the address 0 */
modbus_read_registers(mb, 0, 5, tab_reg);
modbus_close(mb);
} // modbus_free invoked, even in the case of exception.
当然,这是假设有唯一的所有权
事实上,这似乎是一个c风格的API,他们已经完全隐藏了modbus_t
的实现对你作为一个用户(因为你传递指针给自由函数,而不是调用对象成员)。
这意味着您不能开箱即用shared_ptr
(因为它需要定义来调用delete
,这也恰好是错误的调用)。可能是使用调用适当的清理函数(可能是modbus_free
)的自定义删除器的一种方法。然后,您必须使用.get()
来获取原始指针,无论何时您想调用API。
相关文章:
- CLANG 编译器 说:变量"PTR"可能未初始化
- 在以唯一ptr为值的C++映射中,动态内存何时会被销毁
- 将 ptr 传递给 ptr 到 A 作为参数传递给 A 的函数是不好的做法吗?
- 为共享 ptr 向量实现复制 c'tor?
- 字符和整数中 **(ptr+1) 的值差异
- C++:在不中断共享的情况下通过引用传递共享 PTR?
- 如何将派生类从基 ptr 分配给 nlohmann::json
- 引用 std::shared:ptr 以避免引用计数
- 为什么我不能在不进行任何转换的情况下将浮点数放入任何类型的 ptr 中?
- 在调用函数时,ptr** 和 ptr*& 之间是否有区别,或者首选C++?
- 另一种类型的智能ptr,比如具有弱refs的unique_ptr
- 尝试打印出 *ptr++ 的值,以了解它是如何工作的
- 如何控制共享 ptr 引用计数?
- dopen():不以 root 身份运行时"failed to map segment from shared object"
- C++中的指针否定 (!ptr == NULL)
- 从const ptr*转换为ptr*时出现问题
- 无法使用 libtool 将 -shared 参数传递给 g++
- boost::shared_ptr和std::shared-ptr的同居
- 我可以用std::shared_ptr而不是boost::shared-ptr构建boost库吗
- shared-ptr-C++shared_ptr与unique_ptr用于资源管理