Replace fixed size arrays with std::array? Replace fixed size arrays with std::array? arrays arrays

Replace fixed size arrays with std::array?


AFAIK std::array just provides a nicer STL-like interface to deal with rather than normal C-arrays. In terms of performances and capabilities the two choices boil down to be pretty much the same but std::array can be used as a standard container.

Another feature: they might be treated like tuples since they provide tuple-like access functions.

Last but not the least as user2079303 noticed: if your code is going to be used by novice programmers, it can prevent the array decaying process when passing it as an argument.

If you're wondering if you should just replace all your C-style arrays with std::arrays, the answer is yes if you're going to exploit some of the newly available features and/or rewrite some of your code to take advantage of those capabilities. If you're just plain substituting C-arrays with std::arrays (without touching anything else) it might not be worth it.


There is one more thing that I don't see mentioned yet: std::array::at(). Stack corruptions can be really nasty to debug and bugs due to stack corruption can hide for a long while. :( The situtation has become somewhat better with Address Sanitizer. Still, I prefer bound checking over address sanitizer.

In my opinion bound-checked element access is enough reason in itself to use std::array rather than C style arrays.


An additional feature that std::array has is that it can be copy-assigned;

std::array<int, 3> a = {1, 2, 3};std::array<int, 3> b = {4, 5, 6};std::array<int, 3> c = a;         // copy-constructiona = b;                            // copy-assignment