Conversion from boost::shared_ptr to std::shared_ptr?(从 boost::shared_ptr 到 std::shared_ptr 的转换?)
问题描述
我有一个库,它在内部使用 Boost 的 shared_ptr
版本,并且只公开那些.对于我的应用程序,我想尽可能使用 std::shared_ptr
.遗憾的是,这两种类型之间没有直接转换,因为引用计数的内容取决于实现.
I got a library that internally uses Boost's version of shared_ptr
and exposes only those. For my application, I'd like to use std::shared_ptr
whenever possible though. Sadly, there is no direct conversion between the two types, as the ref counting stuff is implementation dependent.
有没有办法让 boost::shared_ptr
和 std::shared_ptr
共享同一个引用计数对象?或者至少从 Boost 版本中窃取 ref-count 而只让 stdlib 版本来处理它?</p>
Is there any way to have both a boost::shared_ptr
and a std::shared_ptr
share the same ref-count-object? Or at least steal the ref-count from the Boost version and only let the stdlib version take care of it?
推荐答案
您可以通过使用析构函数携带引用来将 boost::shared_ptr 内部"携带到 std::shared_ptr 中:
You can carry the boost::shared_ptr "inside" the std::shared_ptr by using the destructor to carry the reference around:
template<typename T>
void do_release(typename boost::shared_ptr<T> const&, T*)
{
}
template<typename T>
typename std::shared_ptr<T> to_std(typename boost::shared_ptr<T> const& p)
{
return
std::shared_ptr<T>(
p.get(),
boost::bind(&do_release<T>, p, _1));
}
这样做的唯一真正原因是,如果您有一堆需要 std::shared_ptr<T>
的代码.
The only real reason to do this is if you have a bunch of code that expects std::shared_ptr<T>
.
这篇关于从 boost::shared_ptr 到 std::shared_ptr 的转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从 boost::shared_ptr 到 std::shared_ptr 的转换?


- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 从python回调到c++的选项 2022-11-16
- 静态初始化顺序失败 2022-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- Stroustrup 的 Simple_window.h 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- C++ 协变模板 2021-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 近似搜索的工作原理 2021-01-01