boost::shared_ptr 和 std::shared_ptr 的同居

2023-07-19C/C++开发问题
4

本文介绍了boost::shared_ptr 和 std::shared_ptr 的同居的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我想在某个时候使用 boost::log,但我不能将 std::shared_ptr 作为参数传递,因为编译器 (VS2010) 无法转换将其转换为 boost::shared_ptr.

I want to use boost::log at some point, but I cannot pass a std::shared_ptr as a parameter, because the compiler (VS2010) cannot convert it into a boost::shared_ptr.

我真的不喜欢他们彼此陌生的事实.

I don't really like the fact that they are aliens to one another.

是否有一种安全透明的方式将一种转换为另一种,以免它们相互绊倒?

Is there a safe and transparent way to convert one into the another, so as they don't stumble over each other?

我不认为它与这个问题重复表示两者是相同的.

I don't think it is duplicate of this question that states both are the same.

推荐答案

你可以这样做:

template<typename T>
boost::shared_ptr<T> make_shared_ptr(std::shared_ptr<T>& ptr)
{
    return boost::shared_ptr<T>(ptr.get(), [ptr](T*) mutable {ptr.reset();});
}

template<typename T>
std::shared_ptr<T> make_shared_ptr(boost::shared_ptr<T>& ptr)
{
    return std::shared_ptr<T>(ptr.get(), [ptr](T*) mutable {ptr.reset();});
}

请注意,这不适用于对源 ptr 的弱引用.所以要小心那些!

Note that this does not work with weak references to the source ptr. So be careful with those!

这篇关于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