c++ - 将带有自定义删除器的 unique_ptr 移动到 shared_ptr

标签 c++ c++11 shared-ptr c++14 unique-ptr

我有一个函数可以创建一个带有自定义删除器的 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 中,但鉴于我不知道该怎么做在函数之外不知道我的自定义删除器的 decltype。

我猜它应该是这样的:

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

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

如果可能,shared_ptr 是否会表现良好,并在使用次数达到零时调用我在 give_unique_ptr() 函数中创建的自定义删除器?

最佳答案

如果您知道(或想明确键入)对象的类型,那么您可以这样做:

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

std::shared_ptr 的构造函数将负责删除器。


但是,如果您希望推断出 类型,那么:

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

希望对您有所帮助。

关于c++ - 将带有自定义删除器的 unique_ptr 移动到 shared_ptr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31034461/

相关文章:

c++ - gcc-4.8.1 中 O2 优化级别的推荐警告标志

c++ - 现代x86硬件能否不将单个字节存储到内存中?

c++ - 使用 QJSEngine 从 JavaScript 访问 Qt API

C++ std::set 与自定义 lower_bound

c++ - C++11 基于范围的 for 循环条件是否在每个循环中都得到评估?

c++ - boost shared_ptr 使用默认构造函数

C++ shared_ptr 释放所有权

c++ - 从函数返回对内的unique_ptr后的段错误

c++ - 为什么不调用复制构造函数?

c++ - this 指针和 QSharedPointer