Now that we have std::array
, std::vector
and brace initialization, are C-style arrays still needed?
1 Answer
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? Jun 19, 2013 at 13:53
std::array
contains?