0

A static member may be declared const, but then it must be initialized in the declaration. Consider the following case of a static array to be initialized with code in loops:

class A {
private:
  enum { SIZE = 360 };
  static double* vertices;
public:
  static void staticInit();
};

double* A::vertices = new double[SIZE];
void A::staticInit() {
  double a = 0, b = 0;
  for (int i = 0; i < SIZE; i++, a += .01, b += .02)
    vertices[i] = sin(a) + c2 * sin(b);
}

The code above would work. But if the intent is to make vertices constant, then declaring it const will give a compile error on the staticInit function.

In older C++ I would declare the pointer const, and cast it to non-const just in this function, but today, compilers won't allow this because it is unsafe. Of course, not declaring the pointer const is even less unsafe.

Is there any clean way out?

Dov
  • 8,000
  • 8
  • 46
  • 75

2 Answers2

3

Create a makeVertices function that returns an std::array, then initialize the static value by invoking it:

constexpr std::size_t size = 360;

std::array<double, size> makeVertices()
{
    std::array<double, size> vertices;
    double a = 0, b = 0;

    for (int i = 0; i < size; i++, a += .01, b += .02)
        vertices[i] = sin(a) + c2 * sin(b);

    return vertices;
}

(Both makeVertices and size could be defined inside A.)

class A {
private:
  static std::array<double, size> vertices;
};

std::array<double, size> A::vertices = makeVertices();

Also note the use of constexpr instead of enum to represent compile-time numerical constants - that's idiomatic C++11.

Toby Speight
  • 27,591
  • 48
  • 66
  • 103
Vittorio Romeo
  • 90,666
  • 33
  • 258
  • 416
2

I don't see why you couldn't make everything const that you care about. To simplify the usecase:

const T * const p = Init();

T * Init()
{
    T * result = new T[n];
    for (std::size_t i = 0; i != n; ++i)
      InitOne(result[i]);
    return result;
}

You should be able to apply this scheme to your static class member.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084