将带有自定义deleter的unique_ptr移动到shared_ptr
Move a unique_ptr with custom deleter to a shared_ptr
我有一个函数,它使用自定义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。
相关文章:
- 将对象移动到std::shared_ptr
- 何时在引用或唯一指针上使用移动语义
- 如何从具有移动语义的类对象中生成共享指针
- 将shared_ptr移动到<StructA>shared_ptr<变体<结构A、结构 B>>
- C / C++ 移位/偏移/向左或向右移动位图?
- MSVC将仅移动结构参数解释为指针
- 自定义先决条件对移动分配运算符有效吗
- 返回值优化:显式移动还是隐式
- 当有分配器意识的容器被复制/移动时,反弹分配器是否被复制/移走
- 为什么复制而不是移动数据元素?
- CLANG 编译器 说:变量"PTR"可能未初始化
- 可以使用移动语义更改或改进此C++代码吗?
- 使lambda不可复制/不可移动
- c++在使用指针时移动语义
- 将QGraphicsItem的移动区域限制在多边形区域内
- 在以唯一ptr为值的C++映射中,动态内存何时会被销毁
- SendInput()鼠标移动计算
- 按值 C++ 返回时进行双倍移动
- 唯一 ptr 将所有权移动到包含对象的方法
- 独特的PTR和移动语义