'Is there any way to declare a array, not just its elements, as const?
Using std::array
I can declare both the array itself and it's objects as const.
const std::array<const int,2> a {1,2};
However, if I read the standard correctly, a declaration such as this only declares the array elements const. See this
const int a[2] {1,2};
The reason this matters is that if the complete object, in these cases a
, is const then it's UB to alter any subobjects. If only the subobjects, like a[0]
are const then they can be modified by "transparent replacement" and it's not UB. This is a new change in basic.life as of c++20. See this. It's also clear from the definition of arrays that array elements are subobjects. See this
For instance this would be legal if the complete object (total array) wasn't const.
std::construct_at(&a[0], 5);
So is there any way other than using the std::array
wrapper to declare the complete array const?
Solution 1:[1]
The type of the variable declared in
const int a[2] {1,2};
is "array of 2 const int
" per the rule you linked, but that itself is a const
-qualified type by the resolution of CWG 1059, which can be found in [basic.type.qualifier]/3 of the post-C++20 draft:
An array type whose elements are cv-qualified is also considered to have the same cv-qualifications as its elements.
I don't think there are any const
-qualified array types to non-const
-qualified elements, nor non-const
-qualified array types to const
-qualified elements, although I guess the object replacement rules allow placing elements of different cv-qualification into an array under some circumstances.
So a
is already a const
complete object and modifying it in the suggested way would be UB.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |