c++ - 将 shared_ptr 转换为 void*

标签 c++ boost shared-ptr

我正在使用 libev,它需要将我的数据转换为 void* 以符合其预定义的结构。我需要将 boost::shared_ptr 转换为 void*,然后将 void* 转换回 boost::shared_ptr。这是我执行此操作的代码

void foo(boost::shared_ptr<string>& a_string)
{
 void* data = (void*)a_string.get();
 boost::shared_ptr<string> myString((string*)data);
}

我很确定这工作正常,但是我的代码设置方式我相信所有对我的字符串的 shared_ptr 引用都超出了范围,因为这种转换方法不会增加 use_count,因此 shared_ptr 正在释放内存,而我仍然需要它。

有没有办法手动增加/减少 use_count?理想情况下,我会在转换为 void* 时增加 use_count,将 void* 传递给另一个函数,将 void* 转换回 shared_ptr 并减少 use_count。

或者,如果有人知道这个问题的另一种解决方案,我可以寻求帮助。

最佳答案

唯一真正的方法是在某个地方分配一个 shared_ptr,它会存在足够长的时间,然后设置 void* 指向它。

关于c++ - 将 shared_ptr 转换为 void*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9918625/

相关文章:

C++0x 和 Friend 函数以及 boost::make_shared

C++/错误测试

非交错存储元组的 C++ 容器

c++ - 列表分配错误 <shared_ptr>

python - 使用 boost-python 将 python 变量设置为 C++ 对象指针

python - 从 boost::python::object 列表中获取单个元素,用于 python 例程

c++ - make_shared如何使用非默认内存管理

c++没有匹配函数用于从派生类调用基类方法

python - 导入 swig 生成的模块时,Python 提示缺少删除方法

c++ - C编译器自动版本递增