将带有自定义deleter的unique_ptr移动到shared_ptr

Move a unique_ptr with custom deleter to a shared_ptr

本文关键字:ptr 移动 shared unique 自定义 deleter      更新时间:2023-10-16

我有一个函数,它使用自定义deleter创建一个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);
}

在该函数的客户端代码中,我想将unique_ptr移动到shared_ptr中,但我不知道如何做到这一点,因为我不知道函数外自定义deleter的decltype。

我想它应该是这样的:

auto uniquePtr = give_unique_ptr();
auto sharedPtr = std::shared_ptr<..??..>(std::move(uniquePtr));

我必须写什么而不是以获得正确的类型?

如果可能的话,当shared_ptr的使用计数为零时,它会表现得很好并调用我在give_unique_ptr()函数中创建的自定义deleter吗?

如果您知道(或想要显式键入)对象的类型,那么您可以执行以下操作:

std::shared_ptr<int> sharedPtr(std::move(uniquePtr));

std::shared_ptr的构造函数将负责deletor。


但是,如果您希望推断类型,则:

auto sharedPtr = make_shared_from(std::move(uniquePtr));

其中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));
};

希望能有所帮助。

auto uniquePtr = give_unique_ptr();
auto sharedPtr = std::shared_ptr<decltype(uniquePtr)::element_type>(std::move(uniquePtr));

是的,shared_ptr将存储并稍后使用自定义deleter。