j00*_*0hi 23 c++ shared-ptr unique-ptr c++11 c++14
我有一个函数,它使用自定义删除器创建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);
}
Run Code Online (Sandbox Code Playgroud)
在该函数的客户端代码中,我想移动unique_ptr到a shared_ptr,但我不知道如何做到这一点,因为我不知道我的自定义删除器的decltype在函数之外.
我想它应该看起来像这样:
auto uniquePtr = give_unique_ptr();
auto sharedPtr = std::shared_ptr<..??..>(std::move(uniquePtr));
Run Code Online (Sandbox Code Playgroud)
我需要写什么而不是.. ?? ..来获得正确的类型?
如果这是可能的,那么当它的使用计数达到零时,它会shared_ptr表现得很好并调用我在give_unique_ptr()函数内创建的自定义删除器吗?
Naw*_*waz 19
如果您知道(或想要显式键入)对象的类型,那么您可以这样做:
std::shared_ptr<int> sharedPtr(std::move(uniquePtr));
Run Code Online (Sandbox Code Playgroud)
将建造者std::shared_ptr照顾deletor.
但是,如果您想要推断类型,那么:
auto sharedPtr = make_shared_from(std::move(uniquePtr));
Run Code Online (Sandbox Code Playgroud)
在哪里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));
};
Run Code Online (Sandbox Code Playgroud)
希望有所帮助.
T.C*_*.C. 15
auto uniquePtr = give_unique_ptr();
auto sharedPtr = std::shared_ptr<decltype(uniquePtr)::element_type>(std::move(uniquePtr));
Run Code Online (Sandbox Code Playgroud)
是的,shared_ptr将存储 - 以及以后使用 - 自定义删除器.