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 的转换?
基础教程推荐
- CString 到 char* 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
