lundi 27 février 2017

Is there a way to create a static const class value that is initialized with a loop?

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?

Aucun commentaire:

Enregistrer un commentaire