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

能否使用std::make_unique对动态数组进行花括号初始化?

智能指针管理动态数组的花括号初始化方案

你尝试的几种写法不生效的核心原因是:std::make_unique 的数组特化版本在当前C标准(截至C23)中仅接收数组长度作为参数,默认对数组执行零初始化,没有提供接收初始化列表的重载,因此无法直接通过make_unique传递花括号列表完成初始化。

可行方案

方案1:直接调用unique_ptr构造函数(C++11及以上通用)

这是最简单、无额外依赖的方案,直接配合new的花括号初始化语法即可,编译器会自动推导数组长度:

#include <memory>
// 无需显式指定数组长度,由初始化列表自动推导
std::unique_ptr<int[]> arr(new int[]{1, 1, 2, 4, 5});

注意:该写法仅在new表达式中出现一次裸指针,会立即被unique_ptr接管管理,不存在内存泄漏风险,完全符合RAII规范。

方案2:封装辅助函数适配make_unique风格(C++11及以上)

如果团队代码规范要求禁止显式写new表达式,可以自行封装零成本的辅助函数实现和make_unique一致的调用风格:

#include <memory>
#include <utility>

template<typename T, typename... Args>
std::unique_ptr<T[]> make_unique_arr(Args&&... args) {
    return std::unique_ptr<T[]>(new T[]{std::forward<Args>(args)...});
}

// 调用方式
auto arr = make_unique_arr<int>(1, 1, 2, 4, 5);

方案3:C++20及以上的to_array配合方案

如果使用C++20及更高版本标准,可以借助std::to_array先构造std::array再转移到unique_ptr,不过该方案会产生一次栈上数组的拷贝,仅适合小数组场景:

#include <memory>
#include <array>

auto arr = std::make_unique<std::array<int, 5>>(std::to_array({1,1,2,4,5}));
// 访问元素时需要先解引用:(*arr)[0]

该方案的劣势是需要显式指定数组长度,且访问语法更繁琐,仅适合特定场景使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 11:48:01