我有一个函数可以创建一个带有自定义删除器的 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/