关于T[N]与std::array<T,N>的区别及解决问题的技术问询
Built-in Arrays (
T[N]) vs std::array<T,N>: Key Differences & Solved Problems Great question—this is a common pain point for C++ developers, and Stroustrup’s definitions cut straight to the core of the issue. Let’s break down exactly how these two fixed-size array types differ, and the concrete problems std::array solves to fix the frustrations of built-in arrays.
Core Differences
- Member Functions & STL Integration: Built-in arrays have zero member functions—you can’t call
size(),begin(), orend()directly on them.std::array, by contrast, comes with all the standard container-like members, making it play seamlessly with STL algorithms out of the box. - Array Decay: When you pass a built-in array to a function, it implicitly "decays" to a pointer to its first element. This means you lose all compile-time size information, leading to bugs when trying to calculate the array’s size inside the function.
std::arraynever decays—its size is part of its type, so it’s preserved when passed around. - Value Semantics: Built-in arrays can’t be copied or assigned directly (e.g.,
int a[5]; int b[5] = a;is invalid). You’d have to manually usememcpyor loop through elements to duplicate them.std::arraysupports full value semantics: you can copy, assign, and return them like any other variable. - Boundary Safety: Accessing a built-in array with
[]does no bounds checking—out-of-bounds access is undefined behavior (it might crash, corrupt memory, or silently do nothing).std::arrayoffers theat()member function, which throws astd::out_of_rangeexception if you try to access an index outside the array’s bounds. - Container Compliance:
std::arrayadheres to the C++ Container concept, meaning it works with generic code designed for containers likestd::vectororstd::list. Built-in arrays are a primitive type with no such standardization.
Exactly What Problems std::array Solves
Let’s tie these differences to real-world headaches:
- Eliminates Array Decay Errors: No more buggy
sizeof(arr)/sizeof(arr[0])calculations that fail when the array decays to a pointer. Withstd::array,size()gives you the correct size every time, even when passing the array to functions. - Seamless STL Algorithm Support: You can use
std::sort,std::for_each, or any other STL algorithm directly on astd::arraywithout workarounds. For built-in arrays, you’d have to usestd::begin(arr)andstd::end(arr)(added in C++11) to make them compatible, which is extra boilerplate. - Simplifies Copying & Assignment: Instead of writing custom copy logic for arrays, you can just do
std::array<int,5> b = a;—it’s that simple. This makes code cleaner and less error-prone. - Provides Optional Bounds Checking: The
at()function adds a safety net for debugging. While[]onstd::arraystill doesn’t check bounds (for performance parity with built-in arrays), having the option to useat()helps catch off-by-one errors early. - Unifies Container Interfaces: If you write code that works with
std::array, it’s easier to adapt it to other containers later. For example, a function that takes astd::arraycan be modified to take astd::span(C++20) to work with any contiguous sequence, whereas built-in arrays require special handling.
Example Code Comparison
Built-in Array Pain Point (Decay)
#include <iostream> void print_array(int arr[]) { // This is wrong! arr is a pointer, so sizeof(arr) is pointer size int size = sizeof(arr) / sizeof(arr[0]); for (int i = 0; i < size; ++i) { std::cout << arr[i] << " "; // Undefined behavior if size is wrong } } int main() { int my_arr[5] = {1, 2, 3, 4, 5}; print_array(my_arr); // Output is unpredictable }
std::array Fix
#include <iostream> #include <array> void print_array(const std::array<int, 5>& arr) { // Correct size every time for (int num : arr) { std::cout << num << " "; } } int main() { std::array<int, 5> my_arr = {1, 2, 3, 4, 5}; print_array(my_arr); // Outputs "1 2 3 4 5" correctly // Easy copy std::array<int, 5> another_arr = my_arr; }
内容的提问来源于stack exchange,提问作者Eduard Rostomyan
相关产品推荐
相关产品推荐

