I have a class Agent, which contains a pointer (array) of class ValueContainer.
Now what I have to do is to create an array of Agent first, and then initialize each one of them independently. Also, Agent has no empty constructor due to its nature.
It’s more or less like this:
Agent agent[n];
for (int i...)
{
load values from hd;
create a ValueContainer with this values;
initialize Agent[i] with loaded values;
deallocate the upstated ValueContainer;
}
// agent's constructor copies the VC values in his own VC,
// so there is no problem of pointers
Unfortunately, I keep on running in segmentation fault errors. I tried allocating the array with malloc, with the upstated declaration, making it an array of pointers. Still, I don’t have any results.
Saying that you want to create an array of
Agentwithout initializing those agents is an anachronism. Initialization takes place during construction. You can’t create a thing without doing some kind of initialization.In almost every case, the “right” thing to do in C++ is to use a
vectoror some other Standard container for your array, and thenpush_backnew elements as you create them. You should see if this is the right approach for you. Without knowing anything at all about your application, it probably is.Maybe what you mean (or maybe what you want) is to create memory space for the array, and then initialize them as you load them. This is quite rare, but it does happen. In that case, first you can allocate a
charbuffer that is big enough to hold all your items:…and then use placement-new to initialize your
Agents within this buffer:This is tricky. You have to juggle several things when using placement new:
byte_indexwithin the buffer.Agents first, then destroy the buffer they are in.Agents:Example of #3:
This is risky code in about a million different ways. I can’t stress strongly enough how no matter how space-age and tempting it may be to try to do this, you probably should not do it in production code. Using placement new should be a last resort when absolutely nothing else will work.