Now that we have std::array
, std::vector
and brace initialization, are C-style arrays still needed?

- 129,499
- 52
- 291
- 397

- 3,086
- 1
- 21
- 28
-
@AndyProwl could you be more specific: What are the possible use cases? – infokiller Jun 18 '13 at 20:42
-
1@JohnnyW: What do you think `std::array` contains? – Jesse Good Jun 18 '13 at 20:45
-
1@JesseGood Yes, I know that they are used for the implementation of std::array, but that doesn't mean that non-stdlib developers should use it – infokiller Jun 18 '13 at 20:46
-
1This could be discussed to no end... On one hand, legacy C arrays are necessary for some class implementations. On the other hand, they should not appear in "end-user" code. So, yes and no. – syam Jun 18 '13 at 20:47
1 Answers
One thing that C-style arrays still hold over std::array
is size deduction. You can do the following with C-style arrays, but not really with std::array
:
int arr[] = {1,2,3,4,5}; // no explicit size
Now, we also have another candidate for C-style arrays replacement: std::initializer_list
. Internally, it is backed by some kind of array-like storage, but observe:
#include <initializer_list> // needed
// ...
auto list = {1,2,3,4,5}; // no explicit size, and no explicit type!
And decltype(list) == std::initializer_list<int>
. However, currently, you can't query the size or elements of such an std::initializer_list
at compile-time, as the member-functions aren't marked constexpr
(yet, fixed in C++14). Also, an even bigger problem: std::initializer_list
only provides const
-access to the elements, so you can't mutate them.
But caution: std::initializer_list
s have reference semantics and if they are returned from a function, you'll have a dangling reference to some storage.
In the end, I'd say there's still a place for C-style arrays in some narrow situations and niches, but in the general case, we have better options available now with std::array
and std::initializer_list
.
-
Thanks, nice answer! so if I understand correctly, when it will be possible to query the size of an `initializer_list` in compile time, even this advantage will go away? I guess you can then design a template function to return a std::array and have the size deducted, right? – infokiller Jun 19 '13 at 13:53