This is a good old C array:
int a[10];
And this is a good old C array that is const:
const int b[10];
In C++, there seem to be two ways to define std::arrays that are const:
std::array<const int, 10> c;
const std::array<int, 10> d;
Are these two definitions equivalent? If so, what is the idiomatic one? If not, what are the differences?
Well, the original
const int b[10];is only useful when you can initialize the array, so both of thestd::arrayexamples don’t work in practice.1:
This is the closest to
const int c[10];. The problem is there will be no default constructor for it, and because the elements are not mutable, it’s worthless to use this. You must provide some initialization for it in the constructor. As-is, it will give a compiler error because the default constructor did not initialize the elements.This code means that
cis mutable, but the elements themselves are not. In practice, however, there are no mutations oncthat don’t affect the elements.2:
This means
dis not mutable, but the elements are of mutable typeint. Becauseconstwill propagate to the members, it means the elements are still not mutable by the caller. Similar to the above example, you will need to initializedbecause it’sconst.In practice, they will both behave similarly with respect to mutability, because mutable operations on
arrayalways touch the elements.