You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 07:55:54