c++static-initializer

Avoiding new() in initialization of static members?


The code in question is as follows:

header:


  class Vec3d : public Object {
    public:
      static linearalgebra::Vec3d* X_AXIS;
      static linearalgebra::Vec3d* Y_AXIS;
      static linearalgebra::Vec3d* Z_AXIS;
      static linearalgebra::Vec3d* AXES[3];

      static int f();
  };

implementation:

  Vec3d* Vec3d::X_AXIS = new Vec3d();
  Vec3d* Vec3d::Y_AXIS = new Vec3d();
  Vec3d* Vec3d::Z_AXIS = new Vec3d();
  Vec3d* Vec3d::AXES[3] = {Vec3d::X_AXIS, new Vec3d(),Vec3d::Z_AXIS};

int Vec3d::f() { X_AXIS = AXES[2]; }

Is there a way of not using these new() operators, but without adding any new helper variables?

The types must be exactly as they are, to be compatible with the rest of the program.

EDIT: guessing from the answers, new() must be used if no helper variables are used. Is it true? Thus, I might add the helper variables. This is a compiler--generated code anyway, so no problem, as long as the headers are readable.

Would the following be ok? Now Valgrind says there are no leaks.


  static Vec3d INIT_X_AXIS;
  static Vec3d INIT_Y_AXIS;
  static Vec3d INIT_Z_AXIS;
  static Vec3d INIT_AXES_1;

  Vec3d* Vec3d::X_AXIS = &INIT_X_AXIS;
  Vec3d* Vec3d::Y_AXIS = &INIT_Y_AXIS;
  Vec3d* Vec3d::Z_AXIS = &INIT_Z_AXIS;
  Vec3d* Vec3d::AXES[3] = {Vec3d::X_AXIS, &INIT_AXES_1, Vec3d::Z_AXIS};

Solution

  • Is it ok in C++, if these pointers are never freed?

    Define "OK". Will your program function? Yes. Is it a good idea? No!

    It seems to me that you would be better off with this:

    class Vec3d : public Object {
    public:
        static linearalgebra::Vec3d xAxisMemory;
        static linearalgebra::Vec3d yAxisMemory;
        static linearalgebra::Vec3d zAxisMemory;
        static linearalgebra::Vec3d axesMemory[3];
    
        static linearalgebra::Vec3d* X_AXIS;
        static linearalgebra::Vec3d* Y_AXIS;
        static linearalgebra::Vec3d* Z_AXIS;
        static linearalgebra::Vec3d* AXES[3];
    
        static int f();
    };
    
    
    Vec3d Vec3d::xAxisMemory;
    Vec3d Vec3d::xAxisMemory;
    Vec3d Vec3d::xAxisMemory;
    Vec3d Vec3d::axesMemory[3];
    
    Vec3d* Vec3d::X_AXIS = &xAxisMemory;
    Vec3d* Vec3d::Y_AXIS = &yAxisMemory;
    Vec3d* Vec3d::Z_AXIS = &zAxisMemory;
    Vec3d* Vec3d::AXES[3] = {&axesMemory[0], &axesMemory[1], &axesMemory[2]};