簡體   English   中英

使用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,在該API中,它們已經完全以用戶的modbus_t向您隱藏了modbus_t的實現(因為您將指針傳遞給了自由函數,而不是調用對象成員)。

這意味着您不能直接使用shared_ptr (因為它需要定義來調用delete ,這也恰好是對make的錯誤調用)。 可能有一種使用自定義刪除程序的方法,該自定義刪除程序調用了適當的清除函數(可能是modbus_free )。 然后,您.get()想調用API時都必須使用.get()獲取原始指針。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM