I have a class (struct) that contains a static const std::array
private member. I want this member to be static and constant (non-writable). It looks like as if adding the initialization through static function, breaks the constness of the member array.
I would have expected the compiler to complain when I try to write to the array defined as const. Instead, when I run I get:
- SEGFAULT when using list initializer,
- Ability to write when using said function
Class also provides iterator by just returning std::array iterator. When I initialize std::array through initializer list (outside of struct declaration), then try to modify the element in the array through iterator, I get SEGFAULT, although compiler doesn't complain (somewhat expected and fine).
However, when I initialize the array through another function (in the code below static std::array<int, 4> HalfCircleStatic_init();
, I am able to change the element value, which is not OK.
Worth mentioning the code below was just to reproduce the issue. I really need the ability to initialize the static const array of greater size in a non-trivial way - i.e. using some trigonometric functions.
I can't understand why is this happening. Any help or direction appreciated. Thanks.
I tried this:
#include <iostream>
#include <array>
struct ArrayContainer
{
using iterator = typename std::array<int, 4>::iterator ;
inline constexpr iterator begin() { return iterator(&arr[0]); }
inline constexpr iterator end() { return iterator(&arr[0] + arr.size()); }
private:
static const std::array<int, 4> arr;
static std::array<int, 4> HalfCircleStatic_init();
};
const std::array<int, 4> ArrayContainer::arr = {1,2,3,4};
std::array<int, 4> ArrayContainer::HalfCircleStatic_init() {
std::array<int, 4> retVal{};
for (int i = 0; i < 4; ++i) retVal[i] = i+1;
return retVal;
}
int main() {
ArrayContainer arrCont;
auto it = arrCont.begin();
std::cout << "Value at 0: " << *it << std::endl;
*it = 5;
std::cout << "Value at 0: " << *it << std::endl;
return 0;
}
Produces:
Value at 0: 1
Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)
If I change initializer (definition) to something like:
const std::array<int, 4> ArrayContainer::arr = ArrayContainer::HalfCircleStatic_init();
I get this:
Value at 0: 1
Value at 0: 5
Process finished with exit code 0
Using GCC 8.4 on Ubuntu