从 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>
.
相关文章