Grim Fandango
Grim Fandango

Reputation: 2426

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;
};

Upvotes: 0

Views: 231

Answers (2)

Red.Wave
Red.Wave

Reputation: 4251

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;
};

Upvotes: 1

Remy Lebeau
Remy Lebeau

Reputation: 597051

You could continue to allocate a raw memory block using calloc(), and then use placement-new to construct the struct inside that memory block:

void *buffer = calloc(1, sizeof(LargePodStruct));
LargePodStruct *s = new(buffer) LargePodStruct;

However, you will not be able to use delete to free the struct, you must call its destructor directly and then free() the memory block:

s->~LargePodStruct();
free(buffer);

Upvotes: 3

Related Questions