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

迁移旧C++程序至现代C++时,重置std::unique_ptr<char[]>编译报错求助

问题

将旧C程序迁移至现代C,原程序使用new和delete做动态内存分配,替换为std::unique_ptr后,重置指向字符数组的std::unique_ptr时出现编译错误。目标是移除所有裸new,简化后的代码如下:

#include <memory>

enum class Types {
    ONE,
    TWO,
};

// 根据类型获取缓冲区长度
int get_buffer_len(Types type) {
    if(type == Types::ONE) return 10;
    else if(type == Types::TWO) return 20;
    else return 0;
}

int main() {
    Types type = Types::ONE;
    std::unique_ptr<char[]> msg{};

    auto len = get_buffer_len(type);
    if(len > 0) {
        msg.reset(std::make_unique<char[]>(len));
    }

    // 根据类型获取实际消息
    if(type == Types::ONE) {
        get_message(msg.get());
    }
}

编译错误信息:

error: no matching function for call to 'std::unique_ptr<char []>::reset(std::__detail::__unique_ptr_array_t<char []>)'
| msg.reset(std::make_unique<char[]>(len));
| ~^~~~~~~~~~~~~~~~~~~~~~~

解决方案
  • 直接赋值替代reset调用:将msg.reset(std::make_unique<char[]>(len));修改为msg = std::make_unique<char[]>(len);
  • 若坚持使用reset,需传递原始指针:msg.reset(new char[len]);,但此方法会引入裸new,不符合移除裸指针的目标,因此不推荐。

原因解释

std::unique_ptr::reset的参数要求是原始指针(例如new返回的指针),而std::make_unique<char[]>(len)返回的是std::unique_ptr<char[]>对象,并非原始指针,类型不匹配导致编译错误。

std::unique_ptr支持直接赋值同类型的unique_ptr(会自动转移所有权),因此直接赋值是最简洁且符合移除裸new目标的做法。

内容的提问来源于stack exchange,提问作者DailyLearner

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 19:24:27