将 std::shared_ptr<T> 转换为 void*

MSI*_*SIS 2 c++11

库需要将二进制数据作为void *. \n要共享的数据以shared_ptr<T>.

\n\n

有没有办法投射shared_ptr<T>void *

\n\n

PS:静态投射不起作用:

\n\n

error: invalid static_cast from type \xe2\x80\x98std::shared_ptr<DataPacket>\xe2\x80\x99 to type \xe2\x80\x98void*\xe2\x80\x99\n static_cast<void *>(binData);\n

\n

小智 6

你的做法是错误的。你的问题不是“我需要将 a 解释shared_ptr<T>为 a void*”——你的问题是“我有一个指向对象的智能指针,我需要一个指向该对象的哑指针”。

shared_ptr<T>有一个函数可以做到这一点

shared_ptr<T> smart;

// ... some code here points smart at an object ...

T *dumb1 = smart.get(); // creates a dumb pointer to the object managed by smart
void *dumb2 = smart.get(); // dumb pointers automatically convert to void*
Run Code Online (Sandbox Code Playgroud)

请注意,此创建的哑指针不参与共享所有权方案,因此您必须注意确保对象的生命周期持续到您需要的时间。