如何在C++中将原始指针转换为unique_ptr?
原始指针转unique_ptr的正确实现方式
你不能用std::make_unique来接管已有原始指针——这个函数的作用是动态分配新对象并包装成unique_ptr,不是用来转换已有原始指针的。针对你的场景,有两种直接可行的写法:
方式1:直接构造unique_ptr赋值
// 替换ViewType为m_view实际指向的类型(比如View) m_view = std::unique_ptr<ViewType>(view); m_coloring = std::unique_ptr<ColoringType>(color); m_rendering = std::unique_ptr<RenderingType>(render);
方式2:使用reset()方法接管指针
m_view.reset(view); m_coloring.reset(color); m_rendering.reset(render);
reset()会先释放当前unique_ptr持有的对象(如果存在),再接管传入的原始指针。
必须注意的要点
- 确保原始指针是通过
new分配的内存:unique_ptr默认用delete释放资源,如果是栈指针、malloc分配的内存,会触发未定义行为。 - 确保原始指针没有被其他智能指针或代码持有所有权:否则会出现重复释放内存的问题。
- 如果需要自定义删除器(比如对应
malloc的free),要显式指定:std::unique_ptr<MyType, decltype(&free)> custom_ptr(malloced_ptr, &free);
内容的提问来源于stack exchange,提问作者crueng
相关产品推荐
相关产品推荐

