从 boost::shared_ptr 到 std::shared_ptr 的转换?

2023-07-20C/C++开发问题
6

本文介绍了从 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_ptrstd::shared_ptr 共享同一个引用计数对象?或者至少从 Boost 版本中窃取 ref-count 而只让 stdlib 版本来处理它?

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 的转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&amp;()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6