用typedef结构体增强shared_ptr

Boost shared_ptr with typedef struct

本文关键字:ptr shared 增强 typedef 结构体      更新时间:2023-10-16

我有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。