c++c++98construction

migrating from calloc() to new


I came across a large pod struct, in which I wanted to add a std::vector member.

struct LargePodStruct {
    float x,y,z;
    int *arr;
    int sz;
    ...            // dozens of primitive types
    std::vector<int> the_new_vector;
};

In order to add a vector to this struct, I needed to replace all calloc() instantiations of this struct with new.

Also, I need to instantiate each existing member to zero. However, adding a default constructor which instantiates every member to zero is a mundane task. It's also easy to forget to instantiate a new member in the future.

LargePodStruct::LargePodStruct()
    x(), y(), z(), arr(), sz(), ... // +dozens of instantiations
{}
  1. Is there an easier way to instantiate the primitive members of this struct with less effort?

  2. Is there a good & elegant way to zero-instantiate a union member as well?

.

struct LargePodStruct {
    float x,y,z;
    int *arr;
    int sz;
    ...            
    union { 
        int i;
        void *ptr;
     } u;
    std::vector<int> the_new_vector;
};

Solution

  • template<typename V>
    struct zdf{
        V value;
        zdf():value{}{};
        operator V&(){return value;};
        operator V()const{return value;};
        V operator()const{return value;};
        V& operator(){return value};
    };
    
    struct LargeModernValue{
        zdf<float> x,y,z;
        std::vector<int> arr;
        std::any u;/*std::variant<int,void*> u;*/
        //....
        std::vector<int> theNewVec;
    };