推荐 const std::array& 传递——最高效安全:避免值传递的逐元素拷贝开销,支持右值绑定,语义清晰且零运行时成本;模板可推导 t 和 n 实现泛型;注意不可隐式转换为裸指针或 vector,n 必须为编译期常量。

直接传 const std::array<t n>&</t> —— 这是最高效、最安全的默认方式。
为什么不能只传 std::array<t n></t>(值传递)?
值传递会触发完整拷贝,哪怕 std::array 是栈上对象、没有动态内存,拷贝仍需逐元素复制。对大类型(如 std::array<:string></:string>)或高频调用场景,开销明显。
- 编译器通常无法对值传递的
std::array做 RVO 或 NRVO 优化(它不是“返回值”,也不是临时对象) -
sizeof(std::array<t n>)</t>就是N * sizeof(T),拷贝成本直观可见 - 即使
T是int,也属于不必要操作;现代 C++ 默认拒绝“隐式拷贝”惯性
为什么推荐 const std::array<t n>&</t> 而非 std::array<t n>&</t>?
绝大多数函数只需读取数组内容(比如打印、计算 sum、查找最大值),不需要修改原数组。加 const 不仅语义清晰,还能接受右值临时量:
-
foo(std::array{1,2,3});在 C++17 及以后合法 —— 若形参是std::array<int>&</int>,则编译失败(非常量左值引用不能绑定右值) -
const &避免意外修改,配合-Wwrite-strings等警告更易暴露逻辑错误 - 底层仍是栈地址传递,零运行时开销,且保留全部类型信息(
.size()、.data()、范围 for 全可用)
模板化处理不同大小的 std::array 怎么写?
硬编码 N(如 const std::array<int>&</int>)只能适配一种尺寸。通用函数应靠模板推导:
template <typename t std::size_t n>
void process(const std::array<t n>& arr) {
std::cout <ul>
<li>调用时无需显式指定模板参数:<code>process(my_arr);</code> 编译器自动推导 <code>T</code> 和 <code>N</code>
</li>
<li>若函数还需支持其他容器(如 <code>std::vector</code>),可进一步泛化为接受迭代器对或使用 <code>std::span</code>(C++20)</li>
<li>注意:模板实例化会产生多个函数副本,但这是编译期代价,不影响运行效率</li>
</ul>
<h3>和裸数组、<code>std::vector</code> 混用时要注意什么?</h3>
<p><code>std::array</code> 不能隐式转成裸指针或 <code>std::vector</code>,必须显式桥接:</p>
<ul>
<li>要传给 C API?用 <code>arr.data()</code> 获取 <code>T*</code>,但记得额外传 <code>arr.size()</code> —— <code>std::array</code> 不提供隐式转换</li>
<li>想兼容 <code>std::vector</code>?别在接口层混用;若必须,用 <code>std::span<const t></const></code>(C++20)或自定义模板约束(如 <code>std::ranges::range</code>)</li>
<li>误把 <code>new int[10]</code> 强转成 <code>std::array<int>*</int></code> 是未定义行为 —— <code>std::array</code> 是 POD 类型,但内存布局 ≠ 动态数组</li>
</ul>
<p>真正容易被忽略的是:<code>std::array</code> 的模板参数 <code>N</code> 必须是编译期常量。一旦大小来自运行时输入(比如用户键入的数字),就该换用 <code>std::vector</code> 或 <code>std::span</code>,而不是强行套 <code>std::array</code>。</p></t></typename>C++免费学习笔记(深入):立即使用
在学习笔记中,你将探索 C++ 的入门与实战技巧!











