[英]Move a unique_ptr with custom deleter to a shared_ptr
I have a function which creates a unique_ptr with a custom deleter and returns it: 我有一个函数,它使用自定义删除器创建unique_ptr并返回它:
auto give_unique_ptr() {
auto deleter = [](int* pi) {
delete pi;
};
int* i = new int{1234};
return std::unique_ptr<int, decltype(deleter)>(i, deleter);
}
In the client code of that function, I'd like to move the unique_ptr
into a shared_ptr
, but I don't know how to do that given that I don't know the decltype of my custom deleter outside of the function. 在该函数的客户端代码中,我想将unique_ptr
移动到shared_ptr
,但我不知道该怎么做,因为我不知道函数之外的自定义删除器的decltype。
I guess it should look something like this: 我想它应该看起来像这样:
auto uniquePtr = give_unique_ptr();
auto sharedPtr = std::shared_ptr<..??..>(std::move(uniquePtr));
What do I have to write instead of ..??.. to get the correct type? 我需要写什么而不是.. ?? ..来获得正确的类型?
If this is possible, will the shared_ptr
behave nicely and call my custom deleter created inside the give_unique_ptr()
function when it's usage count reaches zero? 如果这是可能的,那么shared_ptr
会很好地运行并且当它的使用计数达到零时调用在give_unique_ptr()
函数内创建的自定义删除器吗?
If you know (or want to explicitly type) the type of the object, then you can do this: 如果您知道(或想要显式键入)对象的类型 ,那么您可以这样做:
std::shared_ptr<int> sharedPtr(std::move(uniquePtr));
The constructor of std::shared_ptr
will take care of the deletor. std::shared_ptr
的构造函数将处理deletor。
If you, however, want the type to be inferred, then: 但是,如果您想要推断类型 ,那么:
auto sharedPtr = make_shared_from(std::move(uniquePtr));
where make_shared_from
is: make_shared_from
是:
template<typename T, typename D>
std::shared_ptr<T> make_shared_from(std::unique_ptr<T,D> && p)
{
//D is deduced but it is of no use here!
//We need only `T` here, the rest will be taken
//care by the constructor of shared_ptr
return std::shared_ptr<T>(std::move(p));
};
Hope that helps. 希望有所帮助。
auto uniquePtr = give_unique_ptr();
auto sharedPtr = std::shared_ptr<decltype(uniquePtr)::element_type>(std::move(uniquePtr));
And yes, the shared_ptr
will store - and later use - the custom deleter. 是的, shared_ptr
将存储 - 以后使用 - 自定义删除器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.